So basically here I want my navbar routes to change along with login info from the redux reducer, but the routes stay static.
useEffect(() => {
getUserInfo();
console.log(props.userInfo?. isLoggedIn)
if (props?.userInfo?.isLoggedIn == true) {
setUserState(['profile','dashboard','wallet']);
} else {
setUserState(['sign-in','sign-in','sign-in']);
}
},[props])
So here I store my routes in the useState
hook as an array, but this useEffect
hook does not cast until I change the route by a <Link></Link>
component.
I want it to cast as soon as the redux state changes.
CodePudding user response:
const [userState, setUserState] = useState([])
useEffect(() => {
getUserInfo();
console.log(props.userInfo?. isLoggedIn)
if(props?.userInfo?.isLoggedIn == true) {
setUserState(['profile','dashboard','wallet']);
} else {
setUserState(['sign-in','sign-in','sign-in']);
}
},[props,userState])
Add userState in useEffect dependancy array.
CodePudding user response:
Don't store derived state in React state, this is a React anti-pattern. You can simply rendered the UI from the "dependencies" directly. This assumes the component is correctly subscribed to the Redux store and userInfo
is selected state from the store.
const authenticatedRoutes = ['profile','dashboard','wallet'];
const anonymousRoutes = ['sign-in','sign-in','sign-in'];
...
return (
...
{(props.userInfo?.isLoggedIn ? authenticatedRoutes : anonymousRoutes).map(path => {
// compute and return JSX
})}
...
);
A more common/practical solution is to create route protector components that read the userInfo.isLoggedIn
property and conditionally render the protected route/component or redirect to a "safe route". You can read more about general route protection in my answer here.