import {useEffect} from 'react';
import {useRouter} from 'next/router';
const AuthGurd=props=>{
const {children,fallback} = props;
const auth = useAuth();
const router=useRouter();
useEffect(()=>{
if(!router.isReady){
return
}
if(auth.user===null && !window.localStorage.getItem('userData')){
if(router.asPath !=='/'){
router.replace({
pathname:'/login',
query:{returnUrl:router.asPath}
})
}else{
router.replace('/login')
}}
},[router.route])
if(auth.loading || auth.user===null){
return fallback //loader
}
return <>{children}</>
}
export default AuthGurd;
I am trying to use authentication in my project. when running project first-time localstroage not found its return fallback which is loader. Then I have to refresh the page then return to login page.
CodePudding user response:
The reason might be localStorage is not defined in the window object yet.
That means you have to wait until the page is successfully mounted.
Please try this
import {useEffect} from 'react';
import {useRouter} from 'next/router';
const AuthGurd=props=>{
const {children,fallback} = props;
const auth = useAuth();
const router=useRouter();
const [userData, setUserData] = useState({});
useEffect(() => {
setUserData(window.localStorage.getItem('userData'))
}, [])
useEffect(()=>{
if(!router.isReady || !userData){
return
}
if(auth.user===null && !userData){
if(router.asPath !=='/'){
router.replace({
pathname:'/login',
query:{returnUrl:router.asPath}
})
}else{
router.replace('/login')
}}
},[router.route])
if(auth.loading || auth.user===null){
return fallback //loader
}
return <>{children}</>
}
export default AuthGurd;
The important idea is to ensure that localStorage is ready to use after the page is mounted.