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.
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.
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().
Saving data to localStorage in React is super easy: const [data, setData] = useState([]); useEffect(() => { localStorage. setItem('dataKey', JSON. stringify(data)); }, [data]);
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.
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('/');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With