'localStorage ReactJS TOKEN

I am working on some authorization using JWT. I am storing token in localStorage, and login/register/logout works fine for me. But the problem is when I click the LOGIN button and send the req to the backend server, it returns me object USER and TOKEN if the user exists or an error message if the user doesn't exist. On click, the function should navigate on /profile page if the user exists. That happens, but I got a blank page, and when I reload the page it shows me everything. The same is when I click logout, it should clear localStorage and navigate to /home and change the text in a header from 'YOUR PROFILE' to 'Log in', but I must reload manually to see changes.

Login function looks like this.

  const handleLogin = async () => {
try {
  const response = await apiReq.post("/user/login", data);
  console.log(response.data.user);
  window.localStorage.setItem("user", JSON.stringify(response.data.user));
  window.localStorage.setItem("token", response.data.token);
  navigate("/profil");
} catch (err) {
  console.log(err.message);
}

};

Part of header that should change TEXT and ICON :

        <div
      className={`w-full h-1/2 pb-2 uppercase text-sm font-medium text-gray-700 border-b flex items-center justify-between ${
        window.location.pathname === "/prijava" && "hidden"
      }`}
    >
      {token?.length > 0 ? (
        window.location.pathname !== "/profil" ? (
          <div
            onClick={() => navigate("/profil ")}
            className="flex items-center space-x-2  cursor-pointer"
          >
            <span>Vaš profil</span>
            <BiUserCircle size={20} />
          </div>
        ) : (
          <div
            onClick={() => navigate("/") || window.localStorage.clear()}
            className="flex items-center space-x-2  cursor-pointer"
          >
            <span>Odjavi se</span>
            <BiUserCircle size={20} />
          </div>
        )
      ) : (
        <div
          onClick={() => dispatch(handleHeader()) && navigate("/prijava ")}
          className="flex items-center space-x-2  cursor-pointer"
        >
          <span>Prijavi se</span>
          <BiLogInCircle size={20} />
        </div>
      )}

      <div className="flex space-x-2 items-center text-lg cursor-pointer">
        <BsFacebook />
        <BsInstagram />
      </div>
    </div>

I am using redux toolkit to extract data from localStorage :

    import { createSlice } from "@reduxjs/toolkit";

const initialState = {
  token: window.localStorage.getItem("token")
    ? window.localStorage.getItem("token")
    : "",
  currentUser: window.localStorage.getItem("user")
    ? window.localStorage.getItem("user")
    : [],
};

export const userSlice = createSlice({
  name: "user",
  initialState,
  reducers: {},
});

export const {} = userSlice.actions;

export default userSlice.reducer;


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source