Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

381
Views
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 answers
Answer question

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 Report

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!