【问题标题】:what is the best way to handle error in useMutation hook [duplicate]处理useMutation钩子中错误的最佳方法是什么[重复]
【发布时间】:2020-08-30 15:17:55
【问题描述】:

我正在使用 graphql 来完成我的工作,在我的一个用例中,我正在使用 useMutation hook 进行突变,例如添加、插入或删除。

所以这里我有输入字段和按钮,所以点击我想将数据保存在工作正常的数据库中,

我的主要观点是处理react-apollo-graphql in useMutation 中的错误的最佳方法是什么

目前我正在使用 Promise 处理错误,但我知道这不是最好的方法

我正在做的是

    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);
      });

    });
  };

【问题讨论】:

  • 您可以捕获错误或提供onError 回调。有关详细信息,请参阅链接的帖子。

标签: reactjs graphql react-apollo


【解决方案1】:

我只是将它包装在一个 try/catch 范围内:

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
  }
};

【讨论】:

  • hey react apollo graphql 给出了这个{error} 对象,那么这个有什么用呢?
  • 我编辑了答案,我不使用突变的 return {loading, error} 但通常是返回 promise 并包装整个 try/catch。
猜你喜欢
  • 2017-11-13
  • 1970-01-01
  • 1970-01-01
  • 2015-06-12
  • 2017-12-26
  • 1970-01-01
  • 2020-06-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多