skip to Main Content

As the title says, am not able to call the await function on page refresh, Couldn’t find a fix anywhere
Here is the useEffect Code –

useEffect(() => {
    fetchWalletAddress()
      .then((data) => {
        setWalletAddress(data);
        setLoading(false);
      })
      .catch((error) => {
        console.log("Error while awaiting for event", error);
        setCouldNotFetch(true);
        setLoading(false);
      });
  }, []);

Here is the fetchWalletAddress function –

export const fetchWalletAddress = async () => {
  const storedWalletAddress = localStorage.getItem("SINGULARITY_ACCOUNT_DATA");
  if (!storedWalletAddress) {
    console.log("Data not found in local storage. Fetching from API...");
    return getSUserDetails()
      .then((data) => {
        console.log("User data", data);
        const addressToSet = data
          ? JSON.parse(data).wallet.accounts.evmPublicAddress[0].publicAddress
          : handleWaitingEvent("login").then((loginData) => {
              return loginData.wallet.accounts.evmPublicAddress[0]
                .publicAddress;
            });
        return addressToSet;
      })
      .catch((error) => {
        console.log("Error while fetching data from API", error);
        throw error;
      });
  } else {
    console.log("Data found in local storage. Using cached data...");
    const addressFromStorage =
      JSON.parse(storedWalletAddress)?.gamePayWallet?.accounts
        .evmPublicAddress[0].publicAddress;
    return Promise.resolve(addressFromStorage);
  }
};

this is the getSingularityUserDetails function –

export const getSUserDetails = async () => {
  try {
    const user = await window.SEvent.getConnectUserInfo();
    return JSON.stringify(user.metaData);
  } catch (err) {
    console.error("Error User Details ->", err);
    throw err;
  }
};

the getSUserDetails is not being called on refreshing the page in react

2

Answers


  1. Based on the provided code, it seems like the issue might be related to asynchronous behavior and handling the promises correctly. When the page is refreshed, the useEffect hook gets triggered, but the fetchWalletAddress function might not complete before the component is unmounted.

    To ensure that the await function is called correctly on page refresh, you can use a combination of useEffect and useState hooks to handle the loading and fetching state.

    we use the useState hook to handle the loading and couldNotFetch states. We also introduce a boolean isMounted flag to prevent setting state on an unmounted component. When the component is unmounted (when the page is refreshed or the component is removed from the DOM), we set the isMounted flag to false using the useEffect cleanup function.

    Please make sure to replace the mock fetchWalletAddress implementation with your actual implementation that fetches the data. Also, ensure that your getSUserDetails function is working correctly to fetch the necessary data.

    With these changes, the useEffect hook will correctly fetch the wallet address when the component mounts (on page load) and avoid any issues related to async behavior during page refresh.

    Login or Signup to reply.
  2. Your fetchWalletAddress function need not be marked as async. You are simply returning the promise from that.

    Secondly, you have some logic around storing things in localStorage. So, clear localStorage and try if the function is called.

    export const fetchWalletAddress = () => {
      const storedWalletAddress = localStorage.getItem("SINGULARITY_ACCOUNT_DATA");
      if (!storedWalletAddress) {
        console.log("Data not found in local storage. Fetching from API...");
        return getSUserDetails()
          .then((data) => {
            console.log("User data", data);
            const addressToSet = data
              ? JSON.parse(data).wallet.accounts.evmPublicAddress[0].publicAddress
              : handleWaitingEvent("login").then((loginData) => {
                  return loginData.wallet.accounts.evmPublicAddress[0]
                    .publicAddress;
                });
            return addressToSet;
          })
          .catch((error) => {
            console.log("Error while fetching data from API", error);
            throw error;
          });
      } else {
        console.log("Data found in local storage. Using cached data...");
        const addressFromStorage =
          JSON.parse(storedWalletAddress)?.gamePayWallet?.accounts
            .evmPublicAddress[0].publicAddress;
        return Promise.resolve(addressFromStorage);
      }
    };
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search