'TypeError: Cannot read properties of null (reading 'accessToken')

I have followed Lama YouTube video for creating E commerece application. I tried to implement the logout feature on the admin page which wasn't done in the tutorial. I grabbed the currentUser in the redux and then made it to null so as to logout. I successfully managed to do that. But now since I am logged out I lost my accessToken and I cannot render my login page and the main admin panel.

//My two requestMethods.jsx

import axios from "axios";

const BASE_URL = "http://localhost:5000/api/";
const TOKEN = JSON.parse(JSON.parse(localStorage.getItem("persist:root")).user)
        .currentUser.accessToken;
console.log(TOKEN);

export const publicRequest = axios.create({
    baseURL: BASE_URL 
});


export const userRequest = axios.create({
    baseURL: BASE_URL,
    headers: {token: `Jhoncena ${TOKEN}`}
});

The token is grabbed here which is currently null.

//My userReducer

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

const userSlice = createSlice({
    name: "user",
    initialState: {
        currentUser: null,
        isFetching: false,
        error: false
    },
    reducers:{
        loginStart: (state)=>{
            state.isFetching = true;
        },
        loginSuccess: (state, action)=>{
            state.isFetching = false;
            state.currentUser = action.payload;
            state.error = false;
        },
        loginFailure: (state)=>{
            state.isFetching = false;
            state.error = true;
        },
        logout: (state) =>{
            state.currentUser = null;
        },
    },
});

export const {loginStart, loginSuccess,loginFailure, logout} = userSlice.actions;
export default userSlice.reducer;


//My apiCalls

//USER LOGIN
export const login = async (dispatch,user)=>{
    dispatch(loginStart());

    try {
        const res = await publicRequest.post("/auth/login",user)
        dispatch(loginSuccess(res.data));
    } 
    catch (err) 
    {
        dispatch(loginFailure());
        console.log(err);    
    }
}

//USER LOGOUT
export const userlogout = async(dispatch)=>{
    dispatch(logout());
}

and my topbar where logout is initiated with onClick function

import React from "react";
import { NotificationsNone, Language, Settings} from "@material-ui/icons";
import "./topbar.css";
import { useDispatch } from "react-redux";
import { userlogout } from "../../redux/apiCalls";

export default function Topbar() {
  const dispatch = useDispatch();

  const handleClick = ()=>{
    userlogout(dispatch);
  }


  return (
    <div className="topbar">
      <div className="topbarWrapper">
        <div className="topLeft">
          <span className="logo">Ecoflex-Admin</span>
        </div>
        <div className="topRight">
          <div className="topbarIconContainer">
            <NotificationsNone />
            <span className="topIconBadge">2</span>
          </div>
          <div className="topbarIconContainer">
            <Language />
            <span className="topIconBadge">2</span>
          </div>
          <div className="topbarIconContainer">
            <Settings />
          </div>
          <img src="https://img.icons8.com/fluency/96/000000/admin-settings-male.png" alt="" className="topAvatar" />
          <img className="logout" src="https://img.icons8.com/ios-filled/50/000000/exit.png" alt="" onClick={handleClick}/>
        </div>
      </div>
    </div>
  );
}

Here is the ss of what my login route looks like currently enter image description here



Solution 1:[1]

instead of

const TOKEN = JSON.parse(JSON.parse(localStorage.getItem("persist:root")).user)
        .currentUser.accessToken;

write this:

 const TOKEN = () => {
      if (
        JSON.parse(JSON.parse(localStorage.getItem('persist:root')).user)
          .currentUser.accessToken
      ) {
        return JSON.parse(JSON.parse(localStorage.getItem('persist:root')).user)
          .currentUser.accessToken;
      } else { return '' }
    };

Sources

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

Source: Stack Overflow

Solution Source
Solution 1 ynckblw