0

I use function parseJwt to convert token, in console it display object, but when i save it in localstorage it display [object Object], and i cant use JSON.parse it in another component

Console.log In localstorage enter image description here

     localStorage.setItem('response', parseJwt(JSON.stringify(response.data.token)));
      console.log(parseJwt(JSON.stringify(response.data.token)));
  • 2
    Did you want to parse the token first, and then stringify it? `JSON.stringify(parseJwt(response.data.token))`? – Andy Jun 11 '22 at 14:04
  • in localStorage you can put in key or value just primitive type (number, bool, string) To store the object value you can use `JSON.stringify(yourObject)` – mohamed chadad Jun 11 '22 at 14:10

1 Answers1

2

Local storage only supports storing string. So when you try storing an object like that, it won't work as expected. All you need to do, is stringify the object first:

localStorage.setItem('response', JSON.stringify(parseJwt(JSON.stringify(response.data.token))));

And the reason why you're seeing [object Object], is that [object Object] is the default string representation of a JavaScript Object. You can read more about here https://stackoverflow.com/questions/4750225/what-does-object-object-mean#:~:text=%5Bobject%20Object%5D%20is%20the%20default%20string%20representation%20of%20a%20JavaScript,alert(o)%3B%20%2F%2F%20foo

Reto
  • 1,305
  • 1
  • 18
  • 32
Nam
  • 554
  • 4
  • 11