Nextjs -Using Context Api to manage auth sessions casuing an issue on reloading

  Kiến thức lập trình

Backend works fine and it seems to be an issue due to the useEffect hook , It logs me not found user inside of 2nd useEffect and also , the value of user logs null (useruseruser ,null),it immediately redirects to login page , and then the value of user gets updated (useruseruser ,{…user} ). How can i modify my code to resolve this issue . I want to follow the best practises as industry standards and not just a fix. Below is my authContext code

"use client"
import React from 'react'
import { createContext, useState,useEffect } from "react";
import { useRouter } from 'next/navigation';
import  API_BASE_URL  from '../utils/baseURL'
import { usePathname } from 'next/navigation';
import axios from 'axios';
export const userContext = createContext(null);
function AuthContext({ children }) {
    const router=useRouter()
    const pathname = usePathname();
    const [user, setUser] = useState(null);
    const[loadingAuth,setLoadingAuth] = useState(true);
    const openRoutes=['/login','/signup']

    useEffect(() => {
        const authtoken = localStorage.getItem('token');
        console.log("in ue1")
        if (authtoken) {
            axios.get(`${API_BASE_URL}/api/auth`, {
                headers: {
                    'authorization': authtoken
                }
            })
                .then(response => {
                     console.log(response.data)
                    setUser(response.data.user);
                })
                .catch(error => {
                    console.error('Error fetching user data:', error);
                    setUser(null);
                })
                .finally(() => {
                    setLoadingAuth(false); 
                });
        } else {
            setUser(null);
            setLoadingAuth(false); 
        }
    }, []);
    
    
    useEffect(() => {
      console.log("useruseruser",user) 
     
     if (!user && !openRoutes.includes(pathname)) {   
        console.log("not found user")
           router.push('/login');
        }
    }, [!loadingAuth,user]);


    const logout = () => {    
        setUser(null);
        localStorage.removeItem('token'); 
        router.push('/login'); 
    };

    return (
        <userContext.Provider value={{ user, setUser , logout, loadingAuth}}>
            {loadingAuth?<div className=''>Loading.......</div>:children}        
        </userContext.Provider>
    );
}

export default AuthContext;

LEAVE A COMMENT