Home > Enterprise >  How can i save my context data in the local storage?
How can i save my context data in the local storage?

Time:08-29

I have a context crud project. I want to save all data for example when i add, edit user these save in the local storage. How can i do this ? Currently, everything is working normally in the project. Just the data is not saved. Everything is lost when the page refreshes

import React,{ createContext, useReducer  } from "react";
import AppReducer from "./AppReducer";

const initialState = {
  contacts: [],
};

export const GlobalContext = createContext(initialState);

export const ContextProvider = ({children}) => {
  const [state, dispatch] = useReducer(AppReducer, initialState)

  const ADD_CONTACT = (contacts) => {
    dispatch({
      type: "ADD_CONTACT",
      payload: contacts,
    });
  };

  const REMOVE_CONTACT = (id) => {
    dispatch({
      type: "REMOVE_CONTACT",
      payload: id,
    });
  };

  const UPDATE_CONTACT = (contacts) => {
    dispatch({
      type: "UPDATE_CONTACT",
      payload: contacts,
    });
  };

  return (
    <GlobalContext.Provider
      value={{
        contacts: state.contacts,
        ADD_CONTACT,
        REMOVE_CONTACT,
        dispatch,
        UPDATE_CONTACT,
      }}
    >
      {children}
    </GlobalContext.Provider>
  );
};

CodePudding user response:

You can add local storage function call in your created methods.

const ADD_CONTACT = (contacts) => {
    dispatch({
      type: "ADD_CONTACT",
      payload: contacts,
    });
    // Add new item
    localStorage.setItem('Contacts', 'contacts');
  };

  const REMOVE_CONTACT = (id) => {
    dispatch({
      type: "REMOVE_CONTACT",
      payload: id,
    });
    // Remove item
    localStorage.removeItem('Contacts');
  };

  const UPDATE_CONTACT = (contacts) => {
    dispatch({
      type: "UPDATE_CONTACT",
      payload: contacts,
    });
    // update item
    localStorage.setItem('Contacts', 'contacts');
  };
  • Related