Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

384
Vistas
React.js: Save items after refreshing page

I'm doing a simple Todolist in react.js. So far I'm able to save my objects to LocalStorage, but when I refresh the page the Todo elements are disappearing.

import React, { useState,useEffect } from 'react'
import TodoList from './TodoList.jsx'

const AddTodo = () => {

    const [newTodo, setNewTodo] = useState('')
    const [list, setList] = useState([])
    
    const handleSubmit = () => {

            const todoItem = {
                id:Math.floor(Math.random() * 10000),
                value:newTodo
            }

            if(todoItem){
                setList([...list,todoItem]) 
                setNewTodo('')    
            }
            /*gets the oldlist and whats inside of it and adds the new item */ 
            console.log(list)
            
 
    }

    useEffect(() => {
        localStorage.setItem("list", JSON.stringify(list));
    }, [list])

    useEffect(() => {
        const data = JSON.parse(localStorage.getItem('list'));
        if(data){
            setList(data)
        }
        
    }, [])
   
    return (
        <div className="input_container">
             <form onSubmit={(e) => e.preventDefault()}>
                <input type="text"
                onChange={e => setNewTodo(e.target.value)}
                className="todo-input" 
                placeholder="Write Todo.." 
                value={newTodo} 
                name="text"/>
           
                <button onClick={() => handleSubmit()} className="add-todo-button">
                    Add Todo
                </button>
            </form>

            <TodoList list={list} newTodo={newTodo}/>
          
        </div>
    )
}

export default AddTodo
about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

You have to get the todo list from local storage in your state when you create the state. Every time the page refreshes, it will get the initial state from local storage. If it had something otherwise it will set it to [] like this.

  const [newTodo, setNewTodo] = useState('')
  const [list, setList] = useState(JSON.parse(localStorage.getItem("list")) || [])

This is a better way to do it.

about 4 years ago · Juan Pablo Isaza Denunciar

0

Below part is not useful.

useEffect(() => {
    localStorage.setItem("list", JSON.stringify(list));
}, [list])

When page is mounted, it will set the localStorage as [] because you set [] as default value of list. Here is my solution to help you.

const [list, setList] = useState(JSON.parse(localStorage.getItem("list")) || [])
const handleSubmit = () => {

        const todoItem = {
            id:Math.floor(Math.random() * 10000),
            value:newTodo
        }

        if(todoItem){
            setList([...list,todoItem]) 
            setNewTodo('')    
        }
        /*gets the oldlist and whats inside of it and adds the new item */ 
        console.log(list)

        // Store the value in localStorage
        localStorage.setItem("list", JSON.stringify(list));

}

https://reactjs.org/docs/hooks-effect.html

It would be useful if you can take a look the useEffect again

about 4 years ago · Juan Pablo Isaza Denunciar

0

This effect

    useEffect(() => {
        localStorage.setItem("list", JSON.stringify(list));
    }, [list])

will run every time the component is mounted. Which means that as soon as it's mounted, the effect will run and clear the value stored in the localStorage.

Setting your localStorage value inside your event handler (i.e. handleSubmit) instead of using an effect is a much better approach here.

    const handleSubmit = () => {

            const todoItem = {
                id:Math.floor(Math.random() * 10000),
                value:newTodo
            }

            if(todoItem){
                setList([...list,todoItem]) 
                setNewTodo('')    
            }
            /*gets the oldlist and whats inside of it and adds the new item */ 
            console.log(list)

            // Store the value in localStorage
            localStorage.setItem("list", JSON.stringify(list));
 
    }

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda