T
TanStack•2y ago
exotic-emerald

Error feedback with `createMutation` in `Solid`

I have the following situation:
export function postProgram() {
return createMutation(() => ({
mutationFn: async (program: Partial<Program>) => {
return fetch("http://localhost:4000/api/programs", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ program }),
}).then((res) => {
if (!res.ok) throw new Error("Oops"); // I would like to bubble the API response data instead of throwing an Error
return res.json();
});
},
onError: (error) => {
console.error("error", error);
},
onSuccess: (data) => {
console.log("success", data);
},
}));
}
export function postProgram() {
return createMutation(() => ({
mutationFn: async (program: Partial<Program>) => {
return fetch("http://localhost:4000/api/programs", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ program }),
}).then((res) => {
if (!res.ok) throw new Error("Oops"); // I would like to bubble the API response data instead of throwing an Error
return res.json();
});
},
onError: (error) => {
console.error("error", error);
},
onSuccess: (data) => {
console.log("success", data);
},
}));
}
When calling the API with erroneous data, I get the following response with the status 422:
{
"errors": {
"name": [
"can't be blank"
]
}
}
{
"errors": {
"name": [
"can't be blank"
]
}
}
Because it is not a network error, fetch treats a 422 response as a success. I would like to catch this and trigger a Solid Query error with the actual response from the API to give user feedbacks.
2 Replies
exotic-emerald
exotic-emeraldOP•2y ago
This is a first attempt. It works and I can access the errors via mutation.errors, but it looks dirty:
}).then(async (res) => {
- if (!res.ok) throw new Error("Oops");
+ if (!res.ok) throw (await res.json()).errors;
return res.json();
})
}).then(async (res) => {
- if (!res.ok) throw new Error("Oops");
+ if (!res.ok) throw (await res.json()).errors;
return res.json();
})
Any suggestions how I can improve that? How do you handle it? anyone? I guess not 😅 Will have to wait the release of the online course

Did you find this page helpful?