T
TanStack•3y ago
narrow-beige

react query mutation and async await

Iv'e just seen this code in a PR
const handleSubmit = async (values) => {

useApplication.mutate(values, {
onSuccess: async () => {
window.location.href = `.....`;
},
});
};
const handleSubmit = async (values) => {

useApplication.mutate(values, {
onSuccess: async () => {
window.location.href = `.....`;
},
});
};
surely the async keyword is unnecessary?
8 Replies
flat-fuchsia
flat-fuchsia•3y ago
Yes.
narrow-beige
narrow-beigeOP•3y ago
excellent! noticing a lot of this in this codebase i'm in. both cases i assume? love your blog btw! super helpful
flat-fuchsia
flat-fuchsia•3y ago
yes, both asyncs are not needed unless you use await somewhere.
narrow-beige
narrow-beigeOP•3y ago
thanks> trying to get my head around your last code example on your blog
const fetchTodos = async () => {

try {

// 🚨 await is redundant here, too

return await axios.get('/todos')

} catch (error) {

// 🚨 the catch-and-throw is totally unnecessary

throw error

}

}
const fetchTodos = async () => {

try {

// 🚨 await is redundant here, too

return await axios.get('/todos')

} catch (error) {

// 🚨 the catch-and-throw is totally unnecessary

throw error

}

}
why is the await redundant here its an async functino and a promise is returned by axios? I'd get rid of the return?
flat-fuchsia
flat-fuchsia•3y ago
if you get rid of the try/catch, all you need is:
const fetchTodos = () => {
return axios.get('/todos')
}
const fetchTodos = () => {
return axios.get('/todos')
}
axios returns a failed or resolved promise you might want to extract data though (I kinda forgot that), so it would be:
const fetchTodos = () => {
return axios.get('/todos').then(response => response.data)
}
const fetchTodos = () => {
return axios.get('/todos').then(response => response.data)
}
or, with async/await:
const fetchTodos = async () => {
const response = await axios.get('/todos')
return response.data
}
const fetchTodos = async () => {
const response = await axios.get('/todos')
return response.data
}
narrow-beige
narrow-beigeOP•3y ago
so try /catch isn't a good pattern to use with axios? 'd need to catch an error somehow and try catch seems to be the best way with async/await?
flat-fuchsia
flat-fuchsia•3y ago
it's not a good pattern with react-query. If you catch it in the queryFn, react-query has on way of knowing about the error! Let us catch it for you and just return the promise
narrow-beige
narrow-beigeOP•3y ago
thanks for your help!

Did you find this page helpful?