skip to Main Content

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


  1. Chosen as BEST ANSWER

    Appending .catch to the delete call, and tweaking what the useMutation hook returns fixed the error:

    // Component.js
    import useDeleteMutation from './useDeleteMutation';
      
    export default function Component(){
      const { mutateAsync: delete } = useDeleteMutation();
      
      return (
        <button onClick={() => { delete().catch(e => {}); }}>
         Delete
       </button>
      );
    }
    
    // useDeleteMutation.js
    import { useMutation } from 'react-query';
    
    export default function useDeleteMutation() {
      return useMutation(
        async () => {
          return new Promise(async (resolve, reject) => {
            reject('Simulate failure');
          });
        },
      )
    };
    

    • you can use mutate instead of mutateAsync if you don’t need access to the returned Promise. It will catch errors internally.
    • in v4, you will still see a log statement in the console unless you pass a custom logger that doesn’t write to the console. In v5, we will no longer log failed requests to the console because they are not a "warning" that developers should be alerted about.
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search