使用React
、react-apollo
,我有一个向服务器发送一堆值的突变,服务器返回OK
或NOT 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 } },
});
};
- 您不需要在
handlePriceChange
上使用async
、await
- 即使你这样做了,你也需要在调用突变之前设置状态
- 正如您在评论中提到的,如果您使用
useCallback
,请确保该状态是依赖项列表的一部分