Error handling in useLazyQuery hook of RTK Query?
Asked Answered
B

1

5

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,});
Baghdad answered 27/2, 2022 at 8:27 Comment(1)
Are you sure you actually have an error? have you checked your network devtools and your redux devtools? Also, how are you checking for the error? On next render or within the callback tag called trigger?Apps
F
13

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.

Faiyum answered 14/3, 2022 at 0:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.