【问题标题】:Apollo Client mutation error and updating componentsApollo 客户端突变错误和更新组件
【发布时间】:2018-09-03 23:59:05
【问题描述】:

我有以下代码,我试图决定如何处理错误:

const gqlWrapper = graphql(registerMutation, {
    props: ({ mutate, ownProps }) => ({
        registerUser: userDetails => {
            mutate({
                variables: { ...userDetails },
                update: (proxy, resp) => {
                    // perform update to local state based on success
                }
            }).catch(err => {
                console.log(err);
                // how to update components from here?
            });
        }
    })
});

export default gqlWrapper(Register);

服务器发回一个 GraphQL 错误对象并将其发回,因此它出现在突变的 catch() 块中。如果突变成功,则使用proxy 参数更新组件的数据,但我看不到处理错误的等效方法。

理想情况下,我想更新 catch 块中的 Apollo 缓存,但此时我什至无法向组件或状态注入 props。

最终结果将是在 Register 组件上设置一个 prop/state,该组件显示一个带有条件渲染的错误消息组件。一种方法可能是处理 registerUser 突变起源的错误:

// Where the registerUser mutation get's initiated - on form submit
onSubmit={() => {
    this.props.registerUser(values);
    // the error could be caught here but I don't want this in the UI - I'd rather keep all this outside
}}

但是我觉得这增加了 UI 的体积,我宁愿在页面底部,以及突变功能。有什么方法可以解决这个问题,还是我遗漏了一些明显的东西?

谢谢!

【问题讨论】:

    标签: reactjs react-native graphql react-apollo apollo-client


    【解决方案1】:

    您最好的选择是在您的 Apollo 客户端中使用 https://www.npmjs.com/package/apollo-link-error 之类的东西。这将允许您处理错误并根据这些错误应用您需要的任何自定义逻辑。它也应该允许您将.catch 排除在您的组件之外。其实这个模块在Apollo的documentation是推荐的

    【讨论】:

      猜你喜欢
      • 2017-09-14
      • 2021-10-06
      • 2018-12-19
      • 2020-02-03
      • 2017-09-06
      • 2021-09-03
      • 2018-11-04
      • 2020-03-13
      • 2019-02-02
      相关资源
      最近更新 更多