Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

458
Views
How do I fix this error? Cannot read properties of null
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 |

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Try like this, it should work.

JSON.parse(JSON.parse(localStorage.getItem("persist:root"))?.user || "{}")?.currentUser?.accessToken

about 4 years ago · Juan Pablo Isaza Report

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!