Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Local Storage Keeps Resetting On Page Reload

I'm trying to use local storage to store and array it works but when I reload it resets the array. I have looked through some similar questions and did everything I could understand from the answers provided, so I guessed the problem might be from my code so please help me review it. Thanks in advance

import React, { useState } from 'react'
import Modal from './Modal'


function Boards() {
    const [boards, setboards] = useState([]);
    const [title, settitle] = useState('');

    localStorage.setItem('boards', JSON.stringify(boards));

    let storedboards = JSON.parse(localStorage.getItem('boards')) || [];

    const handleChange = (e) => {
        settitle(e.target.value)
    }
    const handleSubmit = () => {
        if (title.length === 0) {
            return;
        }
        setboards(prev => (
            [
                ...prev,
                title
            ]
        ))
    }
    return (
        <div>
            <ul id="boards">
                <BoardList boards={boards} />
            </ul>
            <Modal title={title} handleChange={handleChange} handleSubmit={handleSubmit} />
        </div>
    )
}
function BoardList({ boards }) {
    const history = useHistory()
    return (
        <>
            {
                boards.map((board, index) => (
                    <li key={index} onClick={() => { history.push('./workspace') }}>
                        <h3>{board}</h3>
                    </li>
                ))}

        </>
    )
}
export default Boards
like image 409
random_dev Avatar asked Nov 29 '25 06:11

random_dev


1 Answers

It's reseting the array when you reload, because of this:

function Boards() {
  // you're creating a state variable with an empty array
  const [boards, setboards] = useState([]);

  // you're overriding the item `boards` on the local storage
  localStorage.setItem('boards', JSON.stringify(boards));

Try a slight change like this:

function Boards() {
  // try to load `boards` from the local storage, if null set empty array to the var
  const storedboards = JSON.parse(localStorage.getItem("boards")) || [];

  // use the above var to create the state variable
  // if you have `boards` in the local storage, the value will be the recovered value
  // otherwise the initial value for this state will be an empty array
  const [boards, setboards] = useState(storedboards);
like image 99
Alberto Anderick Jr Avatar answered Dec 01 '25 19:12

Alberto Anderick Jr