Aximili
Aximili

Reputation: 29484

ReactQuery - How to manipulate data on error

We work with a terrible API where a 404 response means an empty array.

Is there a way to tell React Query to convert 404 error to an empty array?

I am hoping there is a way to do something like this?

const {data, isLoading, isError} = useQuery('key', apiCall, {
    onError: (error) => {
      if(error.statusCode === 404) {
        setData([]);
        setIsError(false);
      }
    }
});

Upvotes: 6

Views: 9349

Answers (2)

TkDodo
TkDodo

Reputation: 28843

react-query only cares about if your query function returns a resolved promise or a rejected promise. How you produce them is up to you. With that in mind, your query function can do more than just making an api call:

const {data, isLoading, isError} = useQuery(
  'key',
  async () => {
    try {
      return apiCall()
    } catch (error) {
      if(error.statusCode === 404) {
        return []
      }
      throw error
    }
  }
);

this will catch all errors, transforms 404 errors into a resolved promise and thus an empty data array, and re-throws all other errors so that they wind up in the error field.

This is potentially a lot better than doing transformations in onError, because with onError, all retries have already happened, so you might get multiple, unnecessary requests. Also, there might be an in-between render cycle where the error is actually rendered on the screen (depends on react batching really).

Upvotes: 12

PCPbiscuit
PCPbiscuit

Reputation: 593

You could do this

const queryClient = useQueryClient();
const emptyResponse = [];

const {data, isLoading, isError} = useQuery(key, apiCall, {
    onError: (error) => {
      if(error.statusCode === 404) {
        queryClient.setQueryData(key, emptyResponse);
      }
    }
});

This will overwrite you current cache in a query

Upvotes: 3

Related Questions