state value set to initial state after using uselazyQuery in React

Viewed 23

When I tried to set signType12 on button click then it firstly set the correct value after that it calls an API via useEffect using useLazyQuery then signType12 gives null as initial state.

Below are the code...

const [getOrder] = useLazyQuery(GET_BUSINESS_LIFE_ORDER, {
fetchPolicy: "no-cache",
onError: useCallback((err: any) => {
  apiErrorHandler(err);
  setIsTransLoading(false);
}, []),
onCompleted: useCallback(({ getBusinessLifeOrder }: any) => {
  setLifeOrder(getBusinessLifeOrder);
  setLoading(false);
  console.log(signType12, "sign12");
  if (getBusinessLifeOrder.signatureId) {
    getOrderSignatureInfo({
      variables: {
        id: orderId,
      },
    });
  } else if (signType12 != null) {
    companySignDoc({
      variables: {
        orderId: orderId,
        deliveryMethod:
          signType12 == "url" ? "URL" : signType12 == "email" ? "EMAIL" : null,
        userType: "LEGALREPRESENTATIVE",
        signer1: {
          name: getBusinessLifeOrder.contactInfo.name,
          email: getBusinessLifeOrder.contactInfo.email,
        },
      },
    });
  }
  // setIsTransLoading(false);
}, []), });

useEffect(() => {
if (signType12) {
  console.log(signType12, “sign12”);
  // setIsTransLoading(true);
  getOrder({ variables: { id: orderId } });
}}, [signType12]);

The return function is

        <button
          onClick={() => {
            setSignType12('url')
          }}>
          Assinar agora
        </button>
        <button
          onClick={() => {
            setSignType12('email')
          }}>
          Enviar documento por email
        </button>
1 Answers

You are facing this issue because this is how useCallback() works in react.

Let's understand:

useCallback(someFunction, []) 
// someFunction will be initialized only once.
// and if you're using any state inside it. 
// state value will be same, that was passed during initialization

Solution:

useCallback(someFunction, [state]) // state which you want to use
Related