use-http icon indicating copy to clipboard operation
use-http copied to clipboard

useFetch does not "rethrow" the exception of an Interceptor

Open Grafikart opened this issue 4 years ago • 5 comments

Describe the bug When an interceptor throw en Error, the get() promise still resolve correctly instead of rejecting

⚠️ Make a Codesandbox ⚠️ https://codesandbox.io/s/quizzical-banach-wejks?file=/src/App.js

To Reproduce Steps to reproduce the behavior:

  1. Use a provider to create an interceptor that throws no matter what
const options = {
  interceptors: {
    response: async ({ response }) => {
      throw new ApiError();
    }
  }
};


ReactDOM.render(
    <UseHTTPProvider options={options}>
      <App />
    </UseHTTPProvider>,
  rootElement
)
  1. Use get to retrieve the data in a child component
  const { get } = useFetch("https://60180601971d850017a3f67e.mockapi.io/get");

  const fetchData = useCallback(async () => {
    try {
      const data = await get();
      console.log(data);
    } catch (e) {
      console.log("Error:", e);
    }
  }, [get]);

Expected behavior I expect the get to throw the error thrown during the interceptor. But I end up with data with a value undefined

Grafikart avatar Feb 18 '21 14:02 Grafikart

Try

  const { get, error } = useFetch("https://60180601971d850017a3f67e.mockapi.io/get")

  const fetchData = useCallback(async () => {
    const data = await get()
    if (error) {
      console.log('error: ', error)
    }
  }, [get, error]);

or

  const { request } = useFetch("https://60180601971d850017a3f67e.mockapi.io/get")

  const fetchData = useCallback(async () => {
    const data = await request.get()
    if (request.error) {
      console.log('error: ', request.error)
    }
  }, [request]);

iamthesiz avatar Feb 22 '21 23:02 iamthesiz

The first snippet of code is not working (error is undefined). I guess the destructuring make me loose the reference.

The second snippet works (data is undefined, and request.error contains my error.

Grafikart avatar Feb 23 '21 16:02 Grafikart

  const { request } = useFetch("https://60180601971d850017a3f67e.mockapi.io/get")

  const fetchData = useCallback(async () => {
    const data = await request.get() // <- this `data` is undefined???
    if (request.error) {
      console.log('error: ', request.error)
    }
  }, [request])

iamthesiz avatar Feb 24 '21 23:02 iamthesiz

Yes this data is undefined ^^

I updated my codesandbox : https://codesandbox.io/s/quizzical-banach-wejks?file=/src/App.js

Grafikart avatar Feb 25 '21 17:02 Grafikart

Expected result: promise should be rejected actual result: promise resolved

It's impossible take correct request.error with multiple queries at same time.

ScriptArtist avatar May 11 '21 21:05 ScriptArtist