Why does the mutate method still resolve instead of reject when the request fails? #4165
-
|
I want the mutate method to reject when the fetch api rejects, instead of returning the cached data. At least give me an option to support this feature. I have a refresh button, I click it to call |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
|
@lovetingyuan the behavior depends on how you call to get a rejecting promise, you need to either use the bound mutate from // option 1: bound mutate (throwOnError defaults to true)
const { mutate } = useSWR('/api/data', fetcher);
try {
await mutate();
} catch (err) {
console.error('refresh failed:', err);
}
// option 2: global mutate with explicit fetcher
import { mutate } from 'swr';
try {
await mutate('/api/data', fetcher('/api/data'), { throwOnError: true });
} catch (err) {
console.error('refresh failed:', err);
}the key distinction is that bare ref: SWR mutation docs |
Beta Was this translation helpful? Give feedback.
@lovetingyuan the behavior depends on how you call
mutate(). when you call it with just a key and no data/fetcher argument (likemutate('/api/data')), it triggers a revalidation, but revalidation errors go to the hook'serrorstate rather than rejecting the promise.to get a rejecting promise, you need to either use the bound mutate from
useSWR(which hasthrowOnError: trueby default) or pass a fetcher explicitly: