Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to wait until localStorage.setItem finishes in angular 4

i am developing an angular 4 application. once the user wants to log in to the system it sends a http request to the server and server validate the user and it sends a reposnce with a authentication key and other user details. i use local storage to save these information

login() {
  if (this.loginForm.valid) {
    this.serviceUserService.authenticate(this.loginForm).subscribe(response => {
      if (response.message != "_err") {
        //saving the current user in localstorage
        localStorage.setItem('currentUser', JSON.stringify(response.body));
        this.router.navigateByUrl('/');
      } else {
        alert("invalid login. Please try again")
      }
    }, err => {
      console.log(err);
    })
  }
}

it seems like that localStorage.setItem() is an asynchronous function. so before it save the curent user in the local storage it redirect to the main page. but since the token is not saved in the local storage no http requests will work. how do i wait until localStorage.setItem() finish it's task and then send the user to home page.

like image 253
pavithra rox Avatar asked Jan 26 '18 07:01

pavithra rox


People also ask

How do I get rid of localStorage after some time?

The only thing you can do is set the delete statement in a timeout of 1 hour. This requires the user to stay on your page or the timeout won't be executed. You can also set an expiration field. When the user revisits your site, check the expiration and delete the storage on next visit as the first thing you do.

Is window localStorage setItem async?

localStorage is a synchronous API. You could defer the setItem method execution with the Promise object, giving them an asynchronous behaviour: const asyncLocalStorage = { setItem: function (key, value) { return Promise. resolve().

How does setItem react in localStorage?

Saving data to localStorage in React is super easy: const [data, setData] = useState([]); useEffect(() => { localStorage. setItem('dataKey', JSON. stringify(data)); }, [data]);

What does localStorage Clear () do?

The clear() method removes all the Storage Object item for this domain. The clear() method belongs to the Storage Object, which can be either a localStorage object or a sessionStorrage object.


1 Answers

You are wrong , all localStorage calls are synchronous. Probably you can add a check before navigating to the next page.

 localStorage.setItem('currentUser', JSON.stringify(response.body));     
 this.router.navigateByUrl('/');
like image 54
Sajeetharan Avatar answered Oct 13 '22 17:10

Sajeetharan