useSWRMutation does not catch error if thrown in fetcher #2602
-
Bug reportDescription / Observed BehaviorThe Expected BehaviorThe error is caught and I can use the Repro Steps / Code Example const authedFetch = useAuthedFetch();
const [name, setName] = useState("");
async function updateName(key: string, { arg }: { arg: string }) {
try {
updateCourseNamePATCH.body.parse({ name: arg });
} catch (error) {
const zodError = error as z.ZodError;
throw new Error(zodError.issues[0].message);
}
try {
const res = await authedFetch(`/courses/${course_id}/name`, {
method: "PATCH",
body: JSON.stringify({ name: arg }),
});
const data = await res.json();
if (!res.ok) {
if (data.error) throw new Error(data.error);
else throw new Error("An unknown error occurred");
}
return data.name;
} catch (error) {
if (error instanceof Error) throw new Error(error.message);
else throw new Error("An unknown error occurred");
}
}
const { error, trigger, isMutating } = useSWRMutation(
`${process.env.NEXT_PUBLIC_API_URL}/courses/${course_id}`,
updateName,
{
revalidate: false,
populateCache: (newCourseName, existingCourseData) => {
return { ...existingCourseData, name: newCourseName };
},
}
); Additional ContextSWR version = 2.1.2 |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 4 replies
-
@joepetrillo As the documentation explains, If you don't want to do that, and want to handle the error through |
Beta Was this translation helpful? Give feedback.
@joepetrillo As the documentation explains,
useSWRMutation
throws an error fromtrigger
by default, so you have to catch and handle it.https://swr.vercel.app/docs/mutation#basic-usage
If you don't want to do that, and want to handle the error through
error
returned fromuseSWRMutation
, you can dothrowOnError = false
so thattrigger
doesn't throw an error.https://swr.vercel.app/docs/mutation#parameters-1