import axios from "axios";
const BASE_URL = "http://localhost:5000/api/";
const TOKEN =
JSON.parse(JSON.parse(localStorage.getItem("persist:root")).User).currentUser
.accessToken || "";
export const publicRequest = axios.create({
baseURL: BASE_URL,
});
export const userRequest = axios.create({
baseURL: BASE_URL,
header: { token: `Bearer ${TOKEN}` },
});
The error:
TypeError: Cannot read properties of null (reading 'User') Module. C:/Users/hp/Desktop/ecommerce 2/client/src/requestMethods.jsx:4 1 | import axios from "axios"; 2 | 3 | const BASE_URL = "localhost:5000/api"; > 4 | const TOKEN = 5 | JSON.parse(JSON.parse(localStorage.getItem("persist:root")).User).currentUser 6 | .accessToken || ""; 7 |
Try like this, it should work.
JSON.parse(JSON.parse(localStorage.getItem("persist:root"))?.user || "{}")?.currentUser?.accessToken
That error message means you tried to access the User property on an object that is null.
The localStorage key persist:root doesn't seem to contain anything. localStorage.getItem can return null, so you need to check for this before attempting to access properties on the value it's returned. For example:
const persistRoot = JSON.parse(localStorage.getItem('persist:root'));
if (persistRoot) {
const accessToken = JSON.parse(persistRoot.User).currentUser.accessToken || '';
}
Depending on how your data is structured, you may need additional checks in that chain to make sure values exist. You may find optional chaining syntax to be useful for this.