i was developing a booking app using MERN STACK ,can you please help me in this error
So the error comes in this part of Code in AuthContext.js file
const INITIAL_STATE = {
user: JSON.parse(localStorage.getItem("user")) || null,
loading: false,
error: null,
}
I used the useEffect
export const AuthContextProvider=({children})=>{
const [state,dispatch]=useReducer(AuthReducer,INITIAL_STATE);
useEffect(() => {
localStorage.setItem("user",JSON.stringify(state.user))
},[state.user]);
and the error which comes
Uncaught SyntaxError: Unexpected token u in JSON at position 0 at JSON.parse () at ./src/context/AuthContext.js
CodePudding user response:
localStorage.get
returns undefined which cannot be parsed by JSON.parse. I usually use a function like this which catches the error and returns the value itself as a fallback.
function parse(value){
try {
return JSON.parse(value)
} catch(_) {
return value
}
}
CodePudding user response:
Error message indicates that issue is within JSON.parse
which is used in INITIAL_STATE
.
You can add guard, something like this:
const userLs = localStorage.getItem("user");
const INITIAL_STATE={
user: userLs ? JSON.parse(userLs) : null,
loading:false,
error:null,
}