Home > Enterprise >  Use React Context With Local Storage
Use React Context With Local Storage

Time:03-13

I am trying to store my array with local storage, but I am not sure how to do it. Also, how would I make it so that with each update in the state, the local storage gets updated at the same time?

Current Code:

import React, { useState, createContext } from 'react';
import { v4 as uuidv4 } from 'uuid';

export const NoteContext = createContext();

export const NoteProvider = props => {

    const [notes, setNotes] = useState([
            {id:uuidv4(), message:'asdfasdfffffffffffffffffffffffffffffffffffffff',title:'New Note', selected:false},
            {id:uuidv4(), message:'asdfffffffffffffffffffffffffffffffffffffff',title:'e', selected:false},
            {id:uuidv4(), message:'asdfasdfffffffffffffffffffffffffffffffffffffff',title:'New Note', selected:false},
    
            {id:uuidv4(), message:'asdfasdfffffffffffffffffffffffffffffffffffffff',title:'New Note', selected:false},
        
            {id:uuidv4(), message:'asdfasdfffffffffffffffffffffffffffffffffffffff',title:'New Note', selected:false},
    
            {id:uuidv4(), message:'asdfasdfffffffffffffffffffffffffffffffffffffff',title:'New Note', selected:false},
    
            {id:uuidv4(), message:'asdfasdfffffffffffffffffffffffffffffffffffffff',title:'New Note', selected:false},
            {id:uuidv4(), message:'asdfasdfffffffffffffffffffffffffffffffffffffff',title:'New Note', selected:false},
            {id:uuidv4(), message:'asdfasdfffffffffffffffffffffffffffffffffffffff',title:'New Note', selected:false}
    
    ])
    return (
        <NoteContext.Provider value={[notes, setNotes]}>
            {props.children}
        </NoteContext.Provider>
    )

}

CodePudding user response:

You can initialize your state from localStorage as well as propagate changes to it using useEffect.

function getInitialState() {
  const notes = localStorage.getItem('notes')
  return notes ? JSON.parse(notes) : []
}

export const NoteProvider = props => {
  const [notes, setNotes] = useState(getInitialState)

  useEffect(() => {
    localStorage.setItem('notes', JSON.stringify(notes))
  }, [notes])
}

CodePudding user response:

Have a look at the localStorage on MDN: https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage

Local storage acts like a map, with key value pairs. In order to set an array into local storage, you'll first have to convert it to json.

localStorage.setItem("notes", JSON.stringify(notes);

To retrieve the items,

const storedNotes = JSON.parse(localStorage.getItem("notes"));

Lastly, you can create a function to update your state and your storage

const updateStorageAndState = (newState) => {
  localStorage.setItem("notes", JSON.stringify(newState));
  setNotes(newState);
}
  • Related