Next.js Discord

Discord Forum

Next-auth with web3 wrapper

Unanswered
Atlantic menhaden posted this in #help-forum
Open in Discord
Atlantic menhadenOP
Using next.js 13.4.11 and app dir. I created this hook to access session if the conditions are met. Is this a good idea or not? Should i created context? I am using this hook in multiple components, some of them are even at the root layout (meaning they are rendered on every page) i dont want to call and check this too much. Any advice is welcomed. Thank you

import { useAccount, useNetwork } from "wagmi";
import {useSession} from "next-auth/react";
import { MyChainId } from "@/lib/crypto/wagmiClient";

export default function useUser() {
    const { data, status } = useSession()
    const { chain } = useNetwork();
    const account = useAccount({
        onConnect({ address, connector, isReconnected }) {
            console.log('Connected', { address, connector, isReconnected });
        },
        onDisconnect() {
            console.log('Disconnected');
        },
    });

    const user = {
        session: null,
        address: account.address,
        currentChain: chain,
        isConnected: account.isConnected,
        isConnecting: account.isConnecting,
        isDisconnected: account.isDisconnected,
    };

    if (account.isConnected && status === "authenticated" && chain?.id === MyChainId
        && data?.user.address === account.address) {
        user.session = data;
    }

    return user;
}

17 Replies

This would depend on what you are using the user object for.
Are you just using it to check if the user is signed into the app?
@Hunter Bertoson Are you just using it to check if the user is signed into the app?
Atlantic menhadenOP
essentially yes.
i am building web3 game, and i only want to be able to access user object if:
1. user is logged in (next auth)
2. user is connected to metamask
3. network chain is polygon
i am displaying user info in sidebar, so i want to avoid displaying wrong info in case user switches accounts in metamask or did not properly log in
Everything looks good, just add a useEffect to check if the user changes the network
or if const { chain } = useNetwork(); already does that for you there is no need.
@Aland or if `const { chain } = useNetwork();` already does that for you there is no need.
Atlantic menhadenOP
yeah it already does
so there is no use for context? to make this context?
bc i dont want to make excessive calls on every page load
bc sidebar is showing everywhere
if you decide to do so i recommend using zustand or nanostores
nanostores is my favorite you can access the state outside of react
@Aland nanostores is my favorite you can access the state outside of react
Atlantic menhadenOP
what is it?
it's a global state manager similiar to context
Atlantic menhadenOP
aha okay
i will look at it