Search code examples
react-nativereact-reduxredux-persist

Can't change persisted redux state


I'm using Redux Persist to save the state of the app so that it's the same when it's closed and opened again. The initial states are saved successfully but I can't seem to update the persisted state with a action. My code is the following:

App.js

import React from "react";
import { createStore } from "redux";
import { persistStore, persistReducer } from "redux-persist";
import storage from "redux-persist/lib/storage";
import reducers from "./src/reducers";
import { Provider } from "react-redux";
import { PersistGate } from "redux-persist/integration/react";
import Router from "./src/Router";

const persistConfig = {
  key: "root",
  storage,
  debug: true
};

const persistedReducer = persistReducer(persistConfig, reducers);

const store = createStore(persistedReducer);
const persistor = persistStore(store);

const App = () => (
  <Provider store={store}>
    <PersistGate loading={null} persistor={persistor}>
      <Router />
    </PersistGate>
  </Provider>
);

export default App;

Schedule reducer

import { strings } from "../../locales/i18n";
import * as types from "../actions/types";

const initialState = strings("schedule.list").map((item, index) => {
  return {
    key: index.toString(),
    title: item.title,
    time: item.time,
    location: item.location,
    description: item.description,
    isFavorite: false
  };
});

const scheduleReducer = (state = initialState, action) => {
  switch (action.type) {
    case types.TOGGLE_FAVORITE:
      state.map(schedule => {
        if (schedule.key === action.id) {
          return (schedule.isFavorite = !schedule.isFavorite);
        }
      });
      return state;
    default:
      return state;
  }
};

export default scheduleReducer;

I can see that the state of isFavorite changes when I call the action but when I reload the app it isn't persisted. What can be the issue here?


Solution

  • map always creates a new array with the result of the callback function, take a look here. In your reducer, you are applying the map function but you are not holding any reference to the new array and returning the existing state, hence there is no change in the state and your state is not being persisted.

    You can change your reducer as follows

    const scheduleReducer = (state = initialState, action) => {
      switch (action.type) {
      case types.TOGGLE_FAVORITE:
        cont updatedState = state.map(schedule => {
          if (schedule.key === action.id) {
            return { 
               ...schedule,
               isFavorite: !schedule.isFavorite 
            };
          }
          return schedule;
        });
        return updatedState;
      default:
        return state;
      }
    };
    

    Hope this will help!