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

160
Views
How can I fix the error How To Fix Unexpected token u in JSON at position 0

I have an error coming from my user reducer code. This is what i have done.

export const userReducer = (
  state = localStorage.getItem('user') !== undefined
    ? JSON.parse(localStorage.getItem('user'))
    : null,
  action
) => {
  switch (action.type) {
    case 'LOGGED_IN_USER':
      return action.payload
    case 'LOGOUT':
      return action.payload
    default:
      return state
  }
}

I don't know if i'm declaring the state very well. I feel thats where the issue is coming from.

I hve tried to declare my state as

export const userReducer = (
  state = localStorage.getItem('user') 
  ? JSON.parse(localStorage.getItem('user')) 
  : null, 
  action
) => {
  switch (action.type) {
    case 'LOGGED_IN_USER':
      return action.payload
    case 'LOGOUT':
      return action.payload
    default:
      return state
  }
}

I still get same error and my page does't load. It renders a blank screen, with the error in the console.

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

0

Here's a "safe" JSON parser, that handles a lot of funky/broken/bad/corrupt JSON:

function jparse(str) { 
    var result = null; 
    try { 
        result = JSON.parse(str) 
    } catch (e) {
        // ignore
    } 
    if (!result) {
        try {
            result = Function('return (' + str + ")")();
        } catch(e){
            // ignore
        }
    }
    return result;
}

console.log( jparse(null) );            // null
console.log( jparse('{bob:"er"}') );    // {bob: 'er'}
console.log( jparse('{\'bob\':"er"}') );// {bob: 'er'}
console.log( jparse('{bob:}') );        // null
console.log( jparse(0) );               // 0
console.log( jparse(false) );           // false
console.log( jparse(undefined) );       // undefined
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!