Search code examples
reactjsreduxredux-toolkitrtk-query

Error handling in useLazyQuery hook of RTK Query?


Following is my implementation of the useLazyQuery hook:

const [trigger,
        { 
    loading: prodLoading,
    error: prodError, 
    data: prodData 
    }
  ] = prodApi.endpoints.getAllProducts.useLazyQuery();

where the result parameter is de-structured into prodLoading, prodError, prodData respectively. When the right parameters are passed to the query, the fetched products can be accessed through the prodData, but on error nothing is accessed through prodError, which brings me to my question, how do we handle errors in the useLazyQuery hook?

Is there any way to get parameters like isLoading, error we use in the useQuery hook?

const {data, error, isLoading, isSuccess} = useGetAllProductsQuery('', {skip,});

Solution

  • Actually, it is exactly the same as the common useQuery's interface. Only one thing worries - seems like you are reading unexisting loading filed, which expected to be isLoading. Besides that, it's straightforward:

    const [trigger, { isLoading, isError, data, error } ] = prodApi.endpoints.getAllProducts.useLazyQuery();
    

    or

    const { data, isLoading, isError, error } = await trigger();
    

    Will be great if you'll log error with isError to the console to check if is actually an error occurred.