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}` },
})
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.