react-querytrpc.io

How to narrow down the type usequery data with suspense and react-error-boundary?


I am using react query

the data received after usequery contains undefined. I want to remove undefined from this data.

usingQuery enter image description here

root.tsx enter image description here

https://tkdodo.eu/blog/react-query-error-handling#error-boundaries

Refer to the above link for error boundary processing. As a result, return "...loading" is done at the end, but return "...loading" is not necessary because I am using error boundaries and suspense. How can I make the function without return "...loading" in this case?

Should I consider HOC?

I tryed https://tkdodo.eu/blog/react-query-error-handling#error-boundaries doc

useQueryOptions { suspense: true, useErrorBoundary: true } and placeholderData initialData

I couldn't get the results I wanted.

"no-non-null-assertion" was also considered, but there were conflicting parts with eslint settings, and there was no way to exclude only certain variables.


Solution

  • I decided to use zod and as a result I solved it with the following code

    // hooks/query.ts
    const useSomeApi = () => {
        const { data } = useQuery(...);
        //userSchema = z.object({name: z.string()});
        const validResult = userSchema.parse(data);
        return {data: validResult}
    }
    

    If subsequent parsing fails, it is processed to throw an error to the error boundary.