Home > Back-end >  React.js: Save items after refreshing page
React.js: Save items after refreshing page

Time:06-16

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

CodePudding user response:

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.

CodePudding user response:

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));
 
    }

CodePudding user response:

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

  • Related