Home > other >  Typescript Chain Async Call
Typescript Chain Async Call

Time:11-22

I need to:

localStorage.setItem('user', user); router.navigate(['/profile']);

The problem is that navigation may occur before storage is set.

Please tell me I don't need to route parameters, create asynchronous classes, callbacks, promisses, or timers for this to work.

CodePudding user response:

You may set localstorage value in useEffect hook like this:

 React.useEffect(()=>{ 
   setStorage()
   router.navigate(['/profile'])      
 },[])
 
 const setStorage = ()=>{  
    localStorage.setItem("user", user)  
 }

It'll set the value in localstorage before router.naviagte

CodePudding user response:

Best way I found (using callback):

this.save(user, response => {
  router.navigate(['/profile']);
})

save(user, callback: (error: any) => void ){
  localStorage.setItem("user", user);
  callback('done');
}
  • Related