score:2

Accepted answer

No you can't pass txnId to props.history.push just after call setTxnId. This because setTxnId is async. Use data.txnId instead. So your code becomes:

const handleSubmit = async (e) => {
  e.preventDefault();
  const { data } = await axios.post(
    "https://api",
    {
      mobile: vmobile,
    }
  );

  setTxnId(data.txnId);

  if (data.txnId) {  // <-- here use data.txnId instead of txnId 
      props.history.push({
      pathname: "/authorise",
      state: { txnId: data.txnId }, // <-- here pass data.txnId instead of txnId 
    });
  }
}

Otherwise, if you want to use txnId just updated, you should use useEffect hook in this way:

useEffect(() => {
   if (txnId) {
      props.history.push({
      pathname: "/authorise",
      state: { txnId: txnId }, 
    });
  }
}, [txnId]);

const handleSubmit = async (e) => {
      e.preventDefault();
      const { data } = await axios.post(
        "https://api",
        {
          mobile: vmobile,
        }
      );

      setTxnId(data.txnId);
}

Related Query

More Query from same tag