swr icon indicating copy to clipboard operation
swr copied to clipboard

Can't catch error using mutate()

Open yqz0203 opened this issue 2 years ago • 2 comments

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.

yqz0203 avatar May 05 '22 09:05 yqz0203

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

promer94 avatar May 13 '22 12:05 promer94

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.

shuding avatar May 15 '22 18:05 shuding

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!

rebelwolfson avatar Oct 26 '22 16:10 rebelwolfson

Oh, btw, I was speaking about unbounded mutate function...

rebelwolfson avatar Oct 26 '22 16:10 rebelwolfson