swr
swr copied to clipboard
Can't catch error using mutate()
Bug report
Description / Observed Behavior
If using mutate without parameters, mutate() always return data even if network has been shut down, the error can not be catch.
This is a pseudo-code example below. In this case, If refresh data when pull down, I can't display an error message to user.
const { mutate } = useSWR('foo', ()=>fetch('my link'))
return <List onPullRefresh={()=>{
mutate().then((data)=>{
console.log(data);
}).catch((e)=>{
toast.show(e.message);
});
} />
Expected Behavior
I hope to get the error which was thrown while fetching in catch
.
you can use the error from swr result or using config callback
const { mutate, error } = useSWR('foo', ()=>fetch('my link'), { onError: (error) => { console.log(error) } })
see: https://codesandbox.io/s/get-from-result-or-callback-02bxw1
I think generally, we need to think again about our error APIs of mutate()
: should it throw right away or set the error state, or both? I'd like to keep this issue open for tracking.
Good time of day! Facing the same issue.
It sounds like it makes sense for mutate
to be able to bypass mutation callback error to handle it via catch
individually. The reason is that you are not always using mutate
in conjunction with useSWR
. It will be annoying to track mutation error only via state hook.
To keep mutate
backwards compatibility, new option, like bypassError
could be introduced, that is false
by default. So the current behavior will stay the same.
Thank you!
Oh, btw, I was speaking about unbounded mutate function...