reactjsgraphqlreact-apollo

Is it possible to retrieve the payload from a mutation completion callback in graphQL?


Using React, react-apollo, I have a mutation that send a bunch of values to the server, and the server returns OK or NOT OK.

I would like to update the values only if the operation, but for this, I need to access the payload in the OnComplete callback.

ex :

  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) />

It looks like it isn't possible without some "tricky" way like using a state ?

EDIT : Tried with state, but doesn't work, the state is null :

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

Solution

    1. You do not need to used async, await on handlePriceChange
    2. Even if you do so, you need to set state before you call the mutation
    3. As you mentioned in your comment, if you are using useCallback, make sure that state is a part of dependency list.