0

ReactJS website, I store using localStorage.setItem("kangaroo", JSON.stringify("banana")); On iPhone it works fine, and I have tested for persistence 1-2 weeks.

But on my Samsung, the localStorage completely disappears after 3-6 days, the timing is random, but I don't know how to prevent it in ReactJS. Is there a way to prevent localStorage from disappearing after a few days on Android?

  • [When is localStorage cleared?](https://stackoverflow.com/questions/8537112/when-is-localstorage-cleared) I've never seen my browser delete localStorage for no reason, it's actually IOS that has moved the folder containing the data to a temp folder that gets emptied more often. – Simone Rossaini Apr 18 '23 at 09:05
  • Yeah, it's funny but it only happens on my samsung Android device when I browse my reactjs website using the google chrome app. It persists, but after a few days when I visit the website again it disappears, even if i visit it daily it disappears one day or another – wynnawinner Apr 18 '23 at 09:20

1 Answers1

1

This may be due to certain settings or optimization services of the Android device automatically clearing the storage space after a period of time.

You may consider using other storage methods instead of localStorage, such as using a third-party library, such as "localForage", which can automatically select the appropriate offline storage method for you.

Here is an example of how to use it:

(async () => {
  try {
    const ordersRaw = await localforage.getItem('ordersRaw');
    const itemsRaw = await localforage.getItem('itemsRaw');
    if (ordersRaw && itemsRaw) {
      // now load the screen
    } else {
      console.log('NO DATA')
    }
  } catch (err) {
    console.log(err);
  }
})();
Lyu PF
  • 33
  • 4
  • Thank you, I will try using localForage to see if it solves the issue – wynnawinner Apr 18 '23 at 09:34
  • I've tried your code and did localforage.setItem("itemsRaw", "item1") console.log(localforage.getItem("itemsRaw")) but it returned [object Promise] in the console instead of "item1" which is what I expected – wynnawinner Apr 18 '23 at 09:48
  • this is my code: – wynnawinner Apr 18 '23 at 10:00
  • async function fetchData() { if (JSON.parse(localForage.getItem("kangaroo")) == null) localForage.setItem("kangaroo", JSON.stringify(banana)); } fetchData(); – wynnawinner Apr 18 '23 at 10:00