0

I am using graphql to do my work, In one of my use-case I am using useMutation hook for doing mutation like add,insert or delete.

So here I have input field and button so on click I want to save data in db which is working fine,

My main point is what is the best way to handle the error in react-apollo-graphql in useMutation

currently I am handling the error using promises but I know that is not the best way to do that

What I am doing is

    const [createDep, {loading,error}] = useMutation(ADD_DEPARTMENTS,{  // here this error I want to do something here ton handle error and loading
    update(_,result){
   console.log(result)
    }
  })
const submitDepartment = (e) => { 
    let dept_name = e.department
    console.log(dept_name)
    createDep({
      variables: { dept_name },
    }).catch((res) => {   // I do not think This is the right way to do
      const errors = res.graphQLErrors.map((error) => {
        console.log(error.message);
      });

    });
  };
vivek singh
  • 417
  • 2
  • 12
  • 36

1 Answers1

1

I am just wrapping it in a try / catch scope:

const [createDep] = useMutation(ADD_DEPARTMENTS, {     
  update(_,result){
    console.log(result)
  }
})

const submitDepartment = async (e) => { 
  let dept_name = e.department
  try {
    await createDep({variables: {dept_name}})
  } catch (err) {
    // handle error here
  }
};
Striped
  • 2,544
  • 3
  • 25
  • 31
  • 1
    hey react apollo graphql gives this `{error}` object so what is the use of this then? – vivek singh May 14 '20 at 07:26
  • I edit the answer, I do not use the return {loading, error} of the mutation but generally the return of the promise and wrapping the whole try/catch. – Striped May 14 '20 at 07:31