Skip to content

Fetch does not throw by default, leading to inconsistent behaviour from react-query #201

@jmunozz

Description

@jmunozz

Fetch does not throw by default, leading to inconsistent behaviour from react-query

Expected behavior

I want to use react-query isError on HTTP errors like 4XX, 5XX...

Actual behavior

Fetch does not throw by default so we have to check response status before going on. React-query recommends to use like below:

useQuery({
  queryKey: ['todos', todoId],
  queryFn: async () => {
    const response = await fetch('/todos/' + todoId)
    if (!response.ok) {
      throw new Error('Network response was not ok')
    }
    return response.json()
  },
})

Instead we do not check fetch response in hook:

export const useAppQuery = ({ url, fetchInit = {}, reactQueryOptions }) => {
  const authenticatedFetch = useAuthenticatedFetch();
  const fetch = useMemo(() => {
    return async () => {
      const response = await authenticatedFetch(url, fetchInit);
      return response.json();
    };
  }, [url, JSON.stringify(fetchInit)]);

  return useQuery(url, fetch, {
    ...reactQueryOptions,
    refetchOnWindowFocus: false,
  });
};

One solution would be forcing fetch to throw on HTTP errors.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions