Home > Enterprise >  Local storage with hooks in react
Local storage with hooks in react

Time:11-05

So I have an array with the following structure:

`

export const transacciones = [
    {
        id:100,
        cantidad: 0,
        concepto : 'Ejemplo',
        descripcion: 'Ejemplo',
        
    },
    
]

` This array will dynamically increase or decrease as I push or filter items in it (Exactly like data in a task list) The problem is that I am trying to add some data persistence using local storage. I guess data is getting stored but not shown when I refresh my browser (chrome). Local storage with 'transacciones' array in it

However, when I refresh data disappears from where it was in the upper image so I`m not even sure if I am correctly storing it.

I've tried two things using useEffect hooks. First aproach:

`

const [transacciones,setTransacciones] = useState([]);

    
    useEffect(()=>{
        localStorage.setItem('transacciones',JSON.stringify(transacciones))
    },[transacciones])
 
    useEffect(() =>{
        const transacciones = JSON.parse(localStorage.getItem('transacciones'))
        if (transacciones){
            setTransacciones(transacciones)
        }
    },[])

` I read somewhere that as the initial value of use state is [] I should chage things in there, so... Second aproach:

`

 const [transacciones,setTransacciones] = useState([],()=>{
        const localData = localStorage.getItem('transacciones');
        return localData ? JSON.parse(localData) : [];
    });


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



` However, when I refresh I get the same result: No persistence.

What am I missing here? Any help would be appreciated

CodePudding user response:

In both scenarios your transacciones array is empty when you perform the localStorage.setItem. if you're trying to keep your local state sync with localStorage this might help:

export function useTransacciones(initialValue){
     const localData = localStorage.getItem('transacciones');
     const [transacciones,_setTransacciones] = useState(localData?JSON.parse(localData) : initialValue); // you can choose your own strategy to handle `initialValue` and cachedValue

     const setTransacciones = (data) => {
        _setTransacciones(data)
        localStorage.setItem(JSON.stringify(data))
     }

     hydrate(){
        const data = localStorage.getItem("transacciones")
        setTransacciones(JSON.prase(data))
     }

     return [ transacciones, setTransacciones, hydrate ]
}

which you can use it anywhere with caching compelexity hidden inside:

const [transacciones, setTransacciones] = useTransacciones([])
  • Related