Update component when connecting through header button

Hi,

I’m quite new to react development. I’ve got a staking component with a connect button. If you connect it shows the balance of the wallet and it verifies if the tokens are approved for staking. This is working correctly.

When I connect through the connect button in the header (different component), the console.log(Moralis.User.current()) is showing the correct address.

const enableAndAuthenticate = async () => {
    await authenticate();
    const currentUser = Moralis.User.current();
    const currentAddress = await currentUser?.get('ethAddress');
    console.log(currentAddress);
  };

In the staking component I’ve got a useEffect useEffect(() => { fetchBalanceOf(userAddress); fetchAllowance(userAddress); fetchAmountWonOnBuy(userAddress); fetchTokensStaked(userAddress); fetchAmountWonOnLottery(userAddress); fetchWon0Tax(userAddress); }, [allowance, tokenToStake, userAddress, user]);

If I understand correctly this should trigger the staking component to rerender as the user changes when I connect in the header. I also tried it using the account but the useEffect doesn’t fetch the required data.

I thought one of the benefits of using moralis is that you don’t need to use react context when wrapping the application in the moralisProvider.

Is there anything I’m doing wrong?

Ok fixed it with a useContext that has the wallet address in state

Typically you update a state variable (e.g. useState) somewhere. I’m not seeing this in your useEffect so your component wouldn’t update unless you were rendering a state variable. In this context, only your useEffect re-runs when one of those dependencies change.

But the user would change when authenticating if I under Correctly so on theory it should rerender or is this not how isAuthenticated and user work?

A component will re-render if a state variable it is using changes. User, etc. won’t do this because it’s not state.

Have a read here: Component State – React (reactjs.org) and Using the State Hook – React (reactjs.org)

A simple fix to this is

const currentUser = await authenticate();
const currentAddress = currentUser.get("ethAddress");
console.log(currentAddress);