You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
What you get as error in onReject is completely determined by what your promiseFn rejects with. It's up to you to make it return something useful. Here's what you could do when using fetch:
constmyFunction=async()=>{try{constres=awaitfetch(url)// try to parse the json, but there might not be anyconstdata=awaitres.json()// resolve or reject with the json response datareturnres.ok ? data : Promise.reject(data)}catch(e){returnPromise.reject(e)// we didn't get valid JSON}}
However, this violates the type for error because it's now the json data, not an Error. There's several ways you can solve that:
Don't reject, but resolve with the error response. In other words just return data regardless of res.ok in the above example. This means you will have to take into account that your resolved data might actually contain an error. Still, it's the easiest solution.
Create a subclass of Error on which you add the response object. This is what useFetch does out of the box.
Use useFetch instead of useAsync and leverage the built-in error handling. When a request fails with useFetch, the error you get is a FetchError which exposes the response object as a property. It won't try to parse any JSON, but you can easily do that yourself. Here's an example:
const[error,setError]=useState()consthandleError=asyncerror=>{try{constdata=awaiterror.response.json()setError(data)}catch(e){setError(e.message)// some other error}}const{ data }=useFetch(url,{/* headers */},{onReject: handleError})
Arguably useFetch should probably try to parse a JSON response even for errors, so this wouldn't be necessary.
Hello,
I'm struggling to get the error JSON response from a useAsync passing through onReject.
const { isPensing } = useAsync({ promiseFn: myFunction, onResolve: (data) => { console.log(data }, onReject: (error) => { // read Bad Request JSON response } })
The JSON Response I would like to read is:
{"id":"7282782728272827","status":"subscribed"}
Any idea ?
Thank you!
The text was updated successfully, but these errors were encountered: