1

Note

My question has been marked duplicate because I i learnt this that localStorage can only save strings. Please refer to original question in that case.

I am trying to read server response .Though this is very straight forward but I am not sure where I am wrong . I am tired of debugging after whole day of work .

This is my response from REST API :

{
    "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoyLCJ1c2VybmFtZSI6Im9rdXNlciIsImV4cCI6MTUxNjYxNDk2MywiZW1haWwiOiJkYWh1QGdhaWwuY29tIiwib3JpZ19pYXQiOjE1MTY2MTEzNjN9.BIno_cz8dQsb63bgobNtSQxpxbzlTfsnvtMr8H3EGVs",
    "user": {
        "pk": 2,
        "username": "okuser",
        "email": "dahu@gail.com",
        "first_name": "",
        "last_name": ""
    }
}

I can save key "token" and use it , but I am not able to get user.pk with this code :

  success: function(data) {

          //save JWT token
          localStorage.token = data.token;
          localStorage.user = data.user; 

The user is am retrieving in some other function like this , where I am actually facing user.pk as undefined :

var user = localStorage.user;
  console.log("user pk : " + user.pk);
  if(!user)
  {
    somethingWentWrongHandler();
    return;
  }

In the above code "user" is present as [object Object] but user.pk is undefined .

Divyanshu Jimmy
  • 2,542
  • 5
  • 32
  • 48

2 Answers2

5

Localstorage holds strings, not objects so when you do localStorage.user = data.user it is just like localStorage.user = data.user.toString();

So you need to stringify it and parse it when you read it.

localStorage.user = JSON.stringify(data.user);  // store it
var user = JSON.parse(localStorage.user)  // read it
epascarello
  • 204,599
  • 20
  • 195
  • 236
0

You can only store string types in local storage. So when you try to save the user object, it is converting it a a string of [object Object].

clarmond
  • 358
  • 1
  • 7