Search code examples
reactjsfunctionreact-hooksjotai

Why "React hook is called in a function" while exporting simple single function that accesses a useAtom state?


I have this simple function that needs to set a state from jotai. I would like this function to have it's own seperate file or be cleaned up somewhere, since it will be reused. I'm new to React and come from Angular. It's kind of a function in a service Angular wise.

How would you solve this properly in React?

Code:

export const setMetamaskWallet = (): void => {
    const [, setWeb3] = useAtom(web3Atom);
    const [, setLoading] = useAtom(loadingAtom);
    const [wallet, setWallet] = useAtom(walletAtom);

    setWeb3(
        new Web3(window.ethereum),
    )

    //Todo: Create check if metamask is in browser, otherwise throw error
    const setAccount = async () => {
        setLoading(true);

        const accounts = await window.ethereum.request(
            {
                method: 'eth_requestAccounts'
            },
        );

        setWallet(
            accounts[0],
        );

        setLoading(false);
    }

    if (!wallet) {
        setAccount();
    }

}

Solution

  • Hooks can only be called in React functional components or other hooks. Here it appears you have called it in a typical function, hence the error. You could package this functionality in a custom hook. It may however be most appropriate to keep this function as it is, and instead of calling hooks within it, pass the relevant data into the function as parameters.