【问题标题】:Apollo client - mutation detect mutation completion and then run codeApollo 客户端 - 突变检测突变完成然后运行代码
【发布时间】:2021-07-11 18:10:15
【问题描述】:

我正在尝试实现更新功能,因此我正在使用 GraphQL 突变。但是,我需要能够检测突变何时完成,以便我可以运行刷新功能。

到目前为止,我的突变:

const handleParameterUpdate = () => {
    let active = true;

    (async() => {
 
        await updateParameterMutation({variables: {
           parameterId: props.parameter.id, 
           newField: newFieldValue;
        }});

        if (!active) {
            return;
        }
        
    })().then(props.updateParams());
    
}

在我的父组件中:

const handleRefresh = () => {
    refetchJobParams({
        id: parent.id
    });
}

我的意图是在突变完成后运行handleRefresh 函数。到目前为止,它在handleParametersUpdate 之后立即运行,因此,我需要刷新以获取新的新参数。

【问题讨论】:

    标签: reactjs graph apollo-client react-apollo


    【解决方案1】:

    我在这里看不到你的 useMutation。但是,useMutation 钩子可以选择添加 onCompleted 回调,该回调将在成功时调用。如果您还从 apollo 查询中重新获取某些内容,那么我建议您也使用 refetchQueries 选项。这可以让您编写更少的代码并让 Apollo 处理重新获取和完成回调。

    Mutation options (onCompleted & refetchQueries)

    不过,使用您的代码,如果您想在 handleParameterUpdate 中运行 handleRefresh,那么您可以提取突变返回的任何值。

    const handleParameterUpdate = async () => {    
        const returnValue = await updateParameterMutation({variables: {
           parameterId: props.parameter.id, 
           newField: newFieldValue;
        }});
    
        // whatever check you need to do on your mutation,
        if (returnValue){
            handleRefresh();
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2017-09-06
      • 2019-02-17
      • 2021-09-03
      • 2021-10-06
      • 2017-09-14
      • 2020-11-27
      • 2020-02-03
      • 2021-11-18
      • 2018-10-15
      相关资源
      最近更新 更多