reactjslocal-storage

Use React Context With Local Storage


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>
    )

}

Solution

  • 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])
    }