I have stored loggedIn state using react redux toolkit.When a user logs in or registers a new account, the loggedIn state is set to true. However, upon refreshing the page, the default value of loggedIn is false, leading to a redirect to the login page. After re-rendering, the loggedIn state becomes true again. This cause unwanted redirect, how to fix this problem.
userSlice.jsx:
name: "user",
initialState: { loggedIn: false, userData: {} },
reducers: {
isLoggedIn(state, action) {
state.loggedIn = action.payload
},
setUserData(state, action) {
state.userData = action.payload;
},
}
app.jsx:
useEffect(() => {
const data = localStorage.getItem("token");
setToken(data);
if (data) {
const user = jwtDecode(data);
dispatch(isLoggedIn(true));
dispatch(setUserData(user));
} else {
dispatch(isLoggedIn(false));
dispatch(setUserData({}));
}
}, []);
message.jsx:
const loggedIn = useSelector((state) => state.user.loggedIn)
useEffect(() => {
if (!loggedIn) navigate("/login");
const newSocket = io("http://localhost:5000");
setSocket(newSocket);
return () => {
if (newSocket) {
newSocket.disconnect();
}
};
}, []);
I want to store loggedIn state according to token stored in local storage. If token is present , then set it to “true” else “false” but due to default value as “false” it makes unexpected redirects.
Avesek is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.