【问题标题】:Is it possible to retrieve the payload from a mutation completion callback in graphQL?是否可以从 graphQL 中的突变完成回调中检索有效负载?
【发布时间】:2021-04-20 02:57:18
【问题描述】:

使用Reactreact-apollo,我有一个向服务器发送一堆值的突变,服务器返回OKNOT OK

我想仅在操作时更新值,但为此,我需要在 OnComplete 回调中访问有效负载。

例如:

  const [updateCardRate] = useMutation<UpdateInfluencerRateCard, UpdateInfluencerRateCardVariables>(UPDATE_CARD_RATE, {
    onCompleted: (e) => {
      // Can I have the variables (not just the response) here ? 
    },
  });


  const handlePriceChange = async (socialAccountType: SocialMediaTypeForRateCard, price: number) => {
    await updateCardRate({ variables: { input: { price, socialAccountType } } });
  };

  return (<button onClick(SocialMediaTypeForRateCard.FACEBOOK, 122) />

如果没有像使用状态这样的“棘手”方式,这似乎是不可能的?

编辑:尝试使用状态,但不起作用,状态为空:

  const [getPayload, setPayload] = useState<any>(null);
  const [prices, setPrices] = useState<any>(priceCards);

  const [updateCardRate] = useMutation<UpdateInfluencerRateCard, UpdateInfluencerRateCardVariables>(UPDATE_CARD_RATE, {
    onError: useCallback((error: ApolloError) => {
      enqueueSnackbar(t(error.message || 'UnexpectedError'), { variant: 'error' });
      setPrices(priceCards);
    }, []),
    onCompleted: useCallback(() => {
      console.log(getPayload); // this is null
    }, []),
  });

  const handlePriceChange = (socialAccountType: SocialMediaTypeForRateCard, price: number) => {
    setPayload({ price, socialAccountType }); // but it s set here
    updateCardRate({
      variables: { input: { price, socialAccountType } },
    });
  };

【问题讨论】:

  • onCompleted 回调不提供 variables 作为参数。所以,我想,一个存储变量对象的简单状态应该可以完成这项工作。
  • 我试过了,但是当我存储状态,然后在 OnComplete 中使用它时,状态仍然设​​置为以前的值,因为我猜组件在调用/响应过程中没有更新。
  • 顺便说一句,我正在使用onCompleted: useCallback(() =&gt; { }, []),
  • 1.你不需要async, await on handlePriceChange, 2. 即使你这样做了,你也需要在调用突变之前设置状态
  • 如果您使用回调,请确保状态是它的依赖项。

标签: reactjs graphql react-apollo


【解决方案1】:
  1. 你不需要在handlePriceChange上使用asyncawait
  2. 即使这样做,也需要在调用突变之前设置状态
  3. 正如您在评论中提到的,如果您使用的是 useCallback,请确保该状态是依赖项列表的一部分。

【讨论】:

    猜你喜欢
    • 2020-11-15
    • 1970-01-01
    • 2021-03-04
    • 1970-01-01
    • 2020-10-15
    • 2018-06-10
    • 1970-01-01
    • 1970-01-01
    • 2011-07-11
    相关资源
    最近更新 更多