GraphQL query is not returning the data at the first fetch itself

28 Views Asked by At

In my NextJS application, I'm using Apollo Client to query the data. This is the code,

  //Redeem earnable item
  const claimableItemId = "5ab7c5ab-7a3d-4a92-a62f-2fbd995955f6";
  const destAddr = "0x387961b46242A42B445D4354d5048329410613a7";
  const [redeemEarnableItem, { data: redeemItem }] = useMutation(
    REDEEM_EARNABLE_ITEM,
    {
      variables: {
        claimableItemId,
        destAddr,
      },
    }
  );

  const {
    loading,
    error,
    data: invoiceDetails,
  } = useQuery(GET_INVOICE_DETAILS, {
    variables: { invoiceID: invoiceId ? invoiceId : null },
    skip: !invoiceId,
  });

  const redeemHandler = async () => {
    const redeemItem = await redeemEarnableItem();
    const id = redeemItem.data.redeemEarnableItem.invoiceID;
    setInvoiceId(id);
    const items = await invoiceDetails?.getInvoiceDetails?.items;
    setTimeout(() => {
      if (items) {
        console.log(items[items.length - 1], "details");
        const newItem = items[items.length - 1];
        setNFTDetails(newItem);
        setStep(STEPS.NFT_CLAIMED);
      }
    }, 2000);
  };

In the "redeemHandler" function, I'm trying to get the invoiceId from the mutation called "redeemEarnableItem" and pass it to the next query method called "GET_INVOICE_DETAILS" and get the invoiceDetails. When I run the "redeemHandler" function, the invoiceId is getting and passing as arguments to the GET_INVOICE_DETAILS query. But the "invoicedetails" is not coming at the 1st fetching. The data only comes when I run the redeemHandler function again. I'm trying to make the function to wait untill the data comes. But It's not working as I expected. Any help on this would be appreciated.

0

There are 0 best solutions below