Search code examples
reactjsredux

localStorage Getting Undefined State


TL;DR: State updates correctly (viewed from Redux DevTools) but does not persist in Local Storage as it says that the state is "undefined" (screenshots attached).

Explanation: I am new to Redux. I am trying to save my state to Local Storage. The state is updating correctly when I view from Redux DevTools and console.log() statements. However, when I check the application's local storage, it shows that the state is undefined.

What I am trying to do: I am adding a service to my cart whenever I press the "Add" button in one of my components (which I then want to save to the Local Storage of the browser).

Here are the screenshots from Redux DevTools and browser's local storage:

enter image description here

enter image description here

Please help me find and fix the issue.

Here is the code of my root component App.js which contains my Redux store and local storage funtions:

import Servicesdata from "./ServicesData";
import { createStore } from "redux";
import reducer from "./Reducer";
import { Provider } from "react-redux";

// Local Storage Functions:
function saveToLocalStorage(state) {
  try {
    const serializedState = JSON.stringify(state);
    localStorage.setItem("state", serializedState);
  } catch (e) {
    console.log(e);
  }
}

function loadFromLocalStorage() {
  try {
    const serializedState = localStorage.getItem("state");
    if (serializedState === null) return undefined;
    return JSON.parse(serializedState);
  } catch (e) {
    console.log(e);
    return undefined;
  }
}

//initial store
const initialStore = {
  services: Servicesdata,
  cart: [],
  bill: 0,
  // quantity: 0,
  total_items: 0, //saves total items in the cart
};

const persistedState = loadFromLocalStorage();

//store
const store = createStore(
  reducer,
  persistedState,
  window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
);

store.subscribe(() => saveToLocalStorage(store.getState));

const App = () => {
  return (
    <Provider store={store}>
        //more code
    </Provider>
  );
};

export default App;

In my Reducer.js, I am just dispatching an INCREASE action to add a new item to the cart.


Solution

  • Change store.getState to store.getState().