Localstorage get item gets previous value

#1

I am using localStorage.getItem/setItem, for jwt authentication.But i have a problem…
getItem always returns the previous value…

My code is here…

auth.service.ts

login(user_model:any):Observable<any>{

    let url = "http://localhost:3000/user/login";
    let body = JSON.stringify(user_model);
    let headers = new Headers({ 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' });
    let options = new RequestOptions({ headers: headers });
    
    return this.http.post( url, body, options)
      .map((response: Response) => {
         
          let token = response.text(); 
          localStorage.setItem('currentUser', JSON.stringify({ token: token}));
          console.log("setToken",token)
     
  
  
      
      });
   
  

}```

main.service.ts

getContacts():Observable{

var currentUser = JSON.parse(localStorage.getItem('currentUser'));
var token = currentUser.token; 
console.log("getToken",currentUser.token)

let url = "http://localhost:3000/contacts/";

let headers = new Headers({ 'Authorization': 'Bearer ' + token, 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });

console.log("headers",headers)


return this.http.get(url,options)
    .map((response: Response) => response.json());

}```

My root page is loginpage but, getItem works before setItem

#2

To avoid race conditions like this (and to make your code more idiomatic and robust), three things you are doing here that should always be avoided:

  • using storage of any type for in-app communication
  • side effects in map
  • using localStorage at all

So what I would do is:

  • change to use Ionic Storage
  • use it only for communication between app runs, not within one, reading only at app startup
  • for within-running app communication, use some sort of Observable in a service provider (most commonly a BehaviorSubject)
  • use that Observable inside getContacts instead of reading from storage
  • move the state modification stuff (that will be calling next on the Subject) out of map and into tap
1 Like
#3

I applied what they said and my problem was solved. Thank you so much… :pray: