Home > Software engineering >  After using optional chaining. Problem Unexpected token u in JSON at position 0
After using optional chaining. Problem Unexpected token u in JSON at position 0

Time:11-30

After using the optional chain, I've received this problem.

Unexpected token u in JSON at position 0

import axios from 'axios'

const BASE_URL = 'http://localhost:5000/api'
const TOKEN = JSON.parse(JSON.parse(localStorage.getItem('persist:root'))?.user)
    ?.currentUser?.accessToken || null

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

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

Edit added: Edit Image

CodePudding user response:

Try this instead:

const TOKEN = JSON.parse(JSON.parse(localStorage.getItem('persist:root'))?.user ?? null)?.currentUser?.accessToken || null;

It is the same as:

const storageItem = localStorage.getItem('persist:root'); // string or null
const parsedObject = JSON.parse(storageItem); // parsed object or null
const parsedUser = JSON.parse(parsedObject?.user ?? null); // parsed user or null
const TOKEN = parsedUser?.currentUser?.accessToken || null; // the token or null

CodePudding user response:

Why are you trying to parse persist:root, this object is set by redux-persist library, which is a copy of your redux store. If you want any data from the store, use the useSelector hook in your React component.

  • Related