Sergey Khmelevskoy
Sergey Khmelevskoy

Reputation: 2544

How to reset localStorage on user side only once?

I have a react app with redux state which is stored in localStorage

The problem is that data structure has changed and some older users get an error. Need a reset.

If I add localStorage.clear() to the code, it will run every time and there will be no point of using storage it at all.

Is it possible to reset localStorage only once with kind of specific flag passed with deploy? Something like css files which have versions, i.e. .css?412uisqfh9-wq different for deploys

Upvotes: 2

Views: 1992

Answers (1)

Vikasdeep Singh
Vikasdeep Singh

Reputation: 21766

You can run localStorage.clear() only once.

What you need to do like below:

if (localStorage.getItem("clearStorage") === "<old version number>") {
  localStorage.clear();
  localStorage.setItem("clearStorage", "<new version number>");
}

In first run only if condition code will execute and after that everytime this condition will be false and will never execute.

Upvotes: 5

Related Questions