jonahgeek
jonahgeek

Reputation: 123

How do I solve this unexpected token o in JSON at position 1?

I set my jwt like this:

return fetch(`URL`, requestOptions)
  .then(handleResponse)
  .then((user) => {
    AsyncStorage.setItem("user", JSON.stringify(user));
    
    return user;
   });

And now I'm trying to retrieve it from AsyncStorage like this in my login reducer

let user = JSON.parse(AsyncStorage.getItem("user")
const initialState = user ? { loggedIn: true, user } : {};

But now I keep getting Uncaught SyntaxError: Unexpected token o in JSON at position 1 at Object.parse (). The error is coming from my login reducer. How can I solve this?

Upvotes: 1

Views: 1530

Answers (2)

Nithish
Nithish

Reputation: 5999

AsyncStorage.getItem Returns a Promise object. So when you call AsyncStorage.getItem("user") it gives you a promise object, hence the error. Actually you should wait till the promise gets resolved. For more info about AsyncStorage please refer this

This can actually be achieved using below ways

  • Using await
let user = await AsyncStorage.getItem("user");
  • Using Promise
AsyncStorage.getItem("user").then(user => {
    //you can access user here
})

Hope this helps.

Upvotes: 1

AmitJS94
AmitJS94

Reputation: 1212

The first parameters of function JSON.parse should be a String, and your data is a JavaScript object, so it will convert to a String [object object], you should use JSON.stringify before pass the data

let user = JSON.parse(JSON.stringify(AsyncStorage.getItem("user")));

Upvotes: 1

Related Questions