Home > Back-end >  When refreshing page state changes problem
When refreshing page state changes problem

Time:12-19

I have been using Nextjs and trying to check if my user is logged in trough local storage, but with my current setup when setAuth is true and if the page is refreshed, state sets up to default empty value, and i would like that it remains true as it was set before.Please help.

export default function App({Component, pageProps}) {
    const [isAuth, setAuth] = useState('')


    useEffect(() => {
        const storage = localStorage.getItem('isAuth')
        setAuth(storage)
    },[])


    useEffect(() => {

        localStorage.setItem("isAuth", isAuth)
    }, [isAuth])


    return (
        <AppContext.Provider
            value={{
                isAuth,
                setAuth
            }}>
            <Layout>
                <Component {...pageProps} />)
            </Layout>
        </AppContext.Provider>
    )
}

CodePudding user response:

You would need to first look at the localStorage value before setting your isAuth state value. And because you are using NextJS, you can check if the component is being rendered on client side before applying any client side logic with this: typeof window !== "undefined"

If the page is undefined, then it is being rendered on server side, therefore you do not want to use the localStorage API and your authStorage variable will be set to false.

So then your initial state would look something like this:

const authStorage = typeof window !== "undefined" && localStorage.getItem('auth')
const [isAuth, setIsAuth] = useState(authStorage ?? null)

This will save you from rendering your component twice. authStorage ?? null means if the value does not exist, set value null. Afterwards, you can continue in your component without the need for useEffect functions.

Your code snippet is missing what would happens when the user is not authenticated, but you could redirect to a login page or make use of the setIsAuth() inside a function to set both the state value and the localStorage value for the next page render.

  • Related