Skip to content

How to listen to external variable changes in React

Hope you’re doing well 🙂

I’ve an “auth.js” file, with an aysnc function to get the userId and then store it in session storage. Here it is:

export let userId = sessionStorage.getItem("userId");

const getUserId = async () => {
  if (token) {
    await axios
      .get(`${baseURL}/auth/user`, {
        headers: {
          authorization: token
        }
      })
      .then(function (response) {
        const { data } = response;
        return sessionStorage.setItem("userId", data.userId);
      })
      .catch(function (err) {
        return undefined;
      });
  }
};
getUserId();

Then I access this variable in all components that need it, in order to make other requests. Example in App.js:

useEffect(() => {
    getActiveGames();
    if (token && userId) {
      getCart();
      getWallet();
      getWalletPayments();
    }
  }, []);

The problem is that, in the first render, the userId comes null (obviously) and I’m trying different ways to update or even re-render, in order to get the updated value, but nothing seems to work. I know there’s somehow a basic solution for this, but I just can’t figure it out.

It would be awesome if you could help 🙂

Answer

i think you can work with sates use a state manager like redux or contex api to update the state userId for exemple:

.then(function (response) {
        const { data } = response;
// here you set your state (userId = data.userId)
        return sessionStorage.setItem("userId", data.userId);
      })

i hope it will works for you