DanielD
tRPC3y ago
4 replies
Daniel

Query data is undefined for a bit and is then populated. How to use with React State?

I have an asychronous submit function that's called upon a button press. It refetches the query with the new values and then uses setProductResponse to set the values... if query.data is truthy, which is almost never is unless I spam the button. I know what the problem is and I've ran into this into the past, but I forgot what's the best way to deal with it. The query data is undefined for a short bit while the data is actually being fetched, so I need to set the state afterwards, but I'm not exactly sure how to do so. I thought .then would resolve it, but it didn't. Any help would be much appreciated!

Here's my code:

  const query = trpc.multiply.useQuery(
    {
      numberOne: Number(numberOne),
      numberTwo: Number(numberTwo),
    },
    { enabled: false }
  );

  // it's intially undefined, but later isn't.  what's the best practice to handle this?
  const submit = async () => {
    query.refetch().then(() => {
      console.log(query);
      if (query.data) {
        console.log("success!");
        setProductResponse({
          product: query.data.product,
          isSuccess: query.isSuccess,
        });
      } else {
        console.log("failure!");
      }
    });
  };
Was this page helpful?