Dev
Dev

Reputation: 385

Redux Toolkit - Save dark mode value to local storage

I'm currently learning redux toolkit and I want to store dark mode state in localStorage so that if the users refresh the page, selected mode stays the same. My application looks like this:

index.js

import ReactDOM from "react-dom";
import { Provider } from "react-redux";
import { configureStore } from "@reduxjs/toolkit";
import darkModeReducer from "./darkModeSlice";
import App from "./App";

const store = configureStore({
  reducer: {
    darkMode: darkModeReducer,
  },
});

ReactDOM.render(
  <Provider store={store}>
      <App />
  </Provider>,
  document.getElementById("root")
);

darkModeSlice.js

import { createSlice } from "@reduxjs/toolkit";

const initialState = {
  darkMode: false,
};

export const darkModeSlice = createSlice({
  name: "darkMode",
  initialState,
  reducers: {
    toggleDarkMode: (state) => {
      state.darkMode = !state.darkMode;
    },
  },
});

export const { toggleDarkMode } = darkModeSlice.actions;

export default darkModeSlice.reducer;

What would be the optimal solution for this? Please note that I only want to store the dark mode state in local storage, so if I add other reducers in the future their values ​​won't be automatically saved there.

Upvotes: 0

Views: 1637

Answers (1)

Codaid
Codaid

Reputation: 41

You could change your initialState in darkModeSlice

const initialState = {
    darkMode: localStorage.getItem("darkMode") || false
}

If localstorage is undefined, it will automatically be false. And when user changes darkMode you store it with :

localStorage.setItem("darkMode", darkMode);

Upvotes: 1

Related Questions