handling errors from mutate() #810
-
I appreciate the library! From the docs, it isn't clear if there is a proper way to handle exceptions thrown during Suppose I want a user's action to trigger a mutation for a specific key (keeping a static key enables sharing between different components). I may want the resulting data or error kept within the swr. For example: let mySWR = useSWR("myKey");
mySWR.mutate(fetchFromAPI).catch((e) => {});
console.log(mySWR.data, mySWR.error)
//if `fetchFromApi` returns a result, `mySWR.data` should have the result and error is undefined
//if `fetchFromApi` throws an error, `mySWR.error` should have the error text and data is undefined But that doesn't quite work. Here is my example: https://codesandbox.io/s/swr-mutate-error-user-example-mxp14 Some problems:
Thoughts ? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Thank you for your codesandbox link! The cause of You can do this: useSWR('key', null) to avoid that behavior. |
Beta Was this translation helpful? Give feedback.
Thank you for your codesandbox link! The cause of
SyntaxError: Unexpected token < in JSON at position 0
is that youruseSWR
doesn't havefetcher
passed in. So it uses the defaultfetch
function, which can't fetch the key since it's not a URL.You can do this:
to avoid that behavior.