After upgrading react-scripts
from v4 to v5, I’m facing a problem with react-query
^3.34.8.
I am rejecting a promise within useMutation
which is causing the runtime error Uncaught (in promise)
:
// Component.js
import useDeleteMutation from './useDeleteMutation';
export default function Component(){
const { mutateAsync: delete } = useDeleteMutation();
return (
<button onClick={delete}>Delete</button>
);
}
// useDeleteMutation.js
import { useMutation } from 'react-query';
export default function useDeleteMutation() {
return useMutation(
async () => {
return Promise.reject('Simulate failure');
},
)
};
Reading this and this it seems I am missing a try/catch. However I have tried adding them (around the call to delete()
and around the Promise.reject
statement) yet the runtime error remains.
Any idea what I’m missing? what else can I wrap in a try/catch? I don’t want to just silence the warning in create-react-app’s config.
Thanks.
2
Answers
Appending
.catch
to thedelete
call, and tweaking what the useMutation hook returns fixed the error:mutate
instead ofmutateAsync
if you don’t need access to the returned Promise. It will catch errors internally.