Francesco Baldan
Francesco Baldan

Reputation: 49

LocalStorage on Angular app return old values if I don't reload the page

I'm making a Angular application. When I login, I get a user id from the server, and I need to store it in the localStorage.

This is the code that do that:

localStorage.setItem('user', userId)  // where "userId" is a string

I'm testing it on Chrome and when I login it shows the the key user and his value is the user id. It seems to work, but when I need to use that id and get it with

localStorage.getItem('user')

I get null.

If I manually reload the page I get the correct value.

Not done yet, if I logout and login with another user, if I want to get the user id I will get the id of the old user logged. To get the new, correct, one I need to manually reload the page again.

I tried to use both localStorage and window.localStorage but the result doesn't change.

Upvotes: 1

Views: 1915

Answers (1)

Muhammad Shareyar
Muhammad Shareyar

Reputation: 822

on your log out, you have to remove your storage value

localStorage.removeItem('user');

Alternatively, you can also clear the whole localStorage with

localStorage.clear();

Upvotes: 1

Related Questions