ccd
ccd

Reputation: 6948

How to update persist redux state once after deploy the client side?

I use localStorage as my persist redux state, the code shows below.

export const loadState = () => {
  try {
    // localStorage.clear();
    const serializedState = localStorage.getItem("state");
    if (serializedState === null) {
      return undefined;
    }
    return JSON.parse(serializedState);
  } catch (err) {
    return undefined;
  }
};
export const saveState = state => {
  try {
    const serializedState = JSON.stringify(state);
    localStorage.setItem("state", serializedState);
  } catch (err) {
    // Ignore write errors.
  }
};

Every time I change my logical reducer, I should run localStorage.clear(); due to update the localStorage so that the project can run correctly. But it is useless to run the clear method every time, it's better to have a way to control this run once after deploy the project to client side.

Upvotes: 1

Views: 970

Answers (2)

Asaf Aviv
Asaf Aviv

Reputation: 11800

Add version to localStorage and compare when to initialize your state from your reducers

before you load your state save the version number

// When you update your reducers increase this 
// version to 0.2 => 0.3 => 0.4
// this should run before you call loadState
localStorage.setItem('version', '0.3');

export const loadState = () => {
  try {
    const version = localStorage.getItem('version');
    // When you update your reducers change this comparison
    // to the version number you set in localStorage
    if (version !== '0.1') {
      // Let reducers initial the state if the version is not identical
      return undefined; 
    }
    const serializedState = localStorage.getItem('state');
    if (serializedState === null) {
      return undefined;
    }
    return JSON.parse(serializedState);
  } catch (err) {
    return undefined;
  }
};

export const saveState = (state) => {
  try {
    const serializedState = JSON.stringify(state);
    localStorage.setItem('state', serializedState);
  } catch (err) {
    // Ignore write errors.
  }
};

Upvotes: 1

Quang Noi Truong
Quang Noi Truong

Reputation: 39

You can use Migrations function of redux-persist. for more detail: https://github.com/rt2zz/redux-persist/blob/master/docs/migrations.md

Upvotes: 0

Related Questions