T
TanStack3y ago
correct-apricot

Could someone explain onSuccess like I was five?

I just don't seem to get this to work logically and can't find an example to explain this properly either. So I have an async function that looks like this:
export const deleteApiContent = async (url: string): Promise<HttpStatusResponse | void> => {
const addr = process.env.REACT_APP_API_URL + url;
let error_msg = "";
let status = 0;
try {
const response = await axios.delete(addr, { headers: authHeader() });
return new Promise<HttpStatusResponse>((resolve, reject) => {
const retval: HttpStatusResponse = {
response: response.data,
status: response.status
}
if (response.status === 200) {
resolve(retval);
} else {
reject(retval);
}
})
} catch (err: any) {
if (err.response) {
error_msg = JSON.stringify(err.response, null, 2);
status = err.response.status;
console.log("server error: " + error_msg);
} else if (err.request) {
error_msg = JSON.stringify(err.request, null, 2);
status = err.request.status;
console.log("no response: " + error_msg);
} else {
error_msg = JSON.stringify(err, null, 2);
console.log("other error: " + error_msg);
}
}
return new Promise<HttpStatusResponse>((resolve, reject) => {
const retval: HttpStatusResponse = {
response: error_msg,
status: status
}
reject(retval);
})
}
export const deleteApiContent = async (url: string): Promise<HttpStatusResponse | void> => {
const addr = process.env.REACT_APP_API_URL + url;
let error_msg = "";
let status = 0;
try {
const response = await axios.delete(addr, { headers: authHeader() });
return new Promise<HttpStatusResponse>((resolve, reject) => {
const retval: HttpStatusResponse = {
response: response.data,
status: response.status
}
if (response.status === 200) {
resolve(retval);
} else {
reject(retval);
}
})
} catch (err: any) {
if (err.response) {
error_msg = JSON.stringify(err.response, null, 2);
status = err.response.status;
console.log("server error: " + error_msg);
} else if (err.request) {
error_msg = JSON.stringify(err.request, null, 2);
status = err.request.status;
console.log("no response: " + error_msg);
} else {
error_msg = JSON.stringify(err, null, 2);
console.log("other error: " + error_msg);
}
}
return new Promise<HttpStatusResponse>((resolve, reject) => {
const retval: HttpStatusResponse = {
response: error_msg,
status: status
}
reject(retval);
})
}
But I can't use this as the mutation function because this can return void. How should I change this function?
1 Reply
correct-apricot
correct-apricotOP3y ago
And I would like this so I don't have to check the status inside useMutation but instead handle errors returned from backend in onError.

Did you find this page helpful?