25

I want to delete or destroy my localStorage content whenever I route to a different component. I want to achieve this so as to avoid the localStorage variable from storing previous values even tho new values are coming in.

Am I on the right path?

Game Component

export class Game implements OnDestroy{    
    constructor(){   
        this.currentGame = JSON.parse(localStorage.getItem('currentGame'));  
    }

    ngOnDestroy(){     
        this.currentGame = null;   
    }
}
TylerH
  • 20,799
  • 66
  • 75
  • 101
XamarinDevil
  • 873
  • 5
  • 17
  • 38
  • 3
    Possible duplicate of [remove value from localstorage javascript](http://stackoverflow.com/questions/14864256/remove-value-from-localstorage-javascript) – Heretic Monkey Apr 26 '17 at 14:46

1 Answers1

100

you can use

localStorage.removeItem('currentGame');

Alternatively, you can also clear the whole localStorage with

localStorage.clear();
Deblaton Jean-Philippe
  • 11,188
  • 3
  • 49
  • 66
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/194979/discussion-between-abhi-and-sam). – Tony Jun 15 '19 at 08:15
  • Can we write localStorage.getItem and localStorage.removeItem in same page? Because I have written it. But I'm removing localStorage on click of a button but the item is getting removed without clicking the button. May be on page load it is getting removed. – Kalyan A Aug 27 '20 at 14:13
  • @Kalyan it looks like your code is executed on page load. Maybe put `alert("I'm beeing executed");` just before removing the item to find out ;-) – Deblaton Jean-Philippe Aug 31 '20 at 06:27
  • @DeblatonJean-Philippe Yes my code is executing on page load... how to handle this? – Kalyan A Sep 01 '20 at 04:43
  • @Kalyan You might have had a wrong ```type``` of your ```button``` or even no type at all. Try using ```type="button"``` – MikhailRatner May 10 '22 at 13:17