Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

382
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda