Home > other >  How I add react-todo-list to localstorage?
How I add react-todo-list to localstorage?

Time:08-14

import React from 'react'
import img from "../components/assets/img/img.svg"
import { ToastContainer } from 'react-toastify';

const Todos = (props) => {

  const { tasks, handleDelete, handleDeleteAll, Checked, tasksChechked } = props;

  const itemsLength = tasks.length;

  return (
    <>
      <ToastContainer autoClose={2000} />
      {
        itemsLength === 0
          ? (
            <div className='todo-list'>
              <div className="todo-img">
                <img src={img} />
                <h6>Heç bir tapşırıq yoxdur</h6>
              </div>
            </div>)
          :
          (<ul className='todo-list'>
            {
              tasks.map((task, index) =>
                <li key={index}
                  className={task.completed ? 'disabled' : ''}
                >
                  <span
                    className='check'
                    onClick={() => Checked(index)}
                    style={{ backgroundColor: task.completed ? '#00A3FF' : "#fff" }}
                  >
                    {task.completed ? <i ></i> : ''}
                  </span>
                  {task.task}
                  <button
                    onClick={() => handleDelete(index)}
                    id='delete'><i ></i></button>
                  <div className="line"></div>
                </li>

              )
            }

          </ul>
          )
      }
      <div className='todo-footer'>
        <p>Ümumi : {itemsLength} tapşırıq</p>
        <p>Hazır : {tasksChechked} tapşırıq</p>
        <button onClick={handleDeleteAll} disabled = {itemsLength===0} >Hamısını sil</button>
      </div>
    </>
  )
}

export default Todos

import React from 'react'
import { useState, useEffect } from 'react'
import Form from './components/Form'
import Todos from './components/Todos'
import { ToastContainer, toast } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';


const App = () => {

  

  
 const [tasks, setTasks] = useState([
    {
      task: "ES 6 standartlarını öyrənmək ",
      completed: false
    },
    {
      task: "filter(), find() funksiyalarının fərqini öyrənmək",
      completed: false
    },
    {
      task: "İngilis dilində 1000 söz əzbərləmək",
      completed: true
    },
    {
      task: "Yeni framework öyrənmək",
      completed: false
    },
    {
      task: "Evə çörək almaq",
      completed: false
    }
  ]);



  const [inputValue, setInputValue] = useState('');

  const [tasksChechked, setTasksChechked] = useState(0);

  useEffect(() => { setTasksChechked(tasks.filter(task => task.completed).length) });

  const handleChange = (e) => {
    setInputValue(e.target.value);
  }

  const formSubmit = (e) => {
    e.preventDefault();
    if (inputValue !== '') {
      const newTask = {
        task: inputValue,
        completed: false,
      }
      setTasks([...tasks, newTask])
      setInputValue('')
      toast.success("Tapşırıq uğurla əlavə edildi");
    }
    else {
      toast.error("Zəhmət olmasa tapşırığı daxil edin");
    }
  }

  const handleDelete = (index) => {
    const newTasks = [...tasks]
    newTasks.splice(index, 1)
    setTasks(newTasks)
    toast.error("Tapşırıq  silindi")

  }

  const handleDeleteAll = () => {
    setTasks([])
    toast("Bütün tapşırıqlar  silindi");
  }

  const Checked = (index) => {
    const newTasks = [...tasks];
    newTasks[index].completed = !newTasks[index].completed;
    setTasks(newTasks);
  }
  return (
    <>
      <div className="content">
        <Form
          inputValue={inputValue}
          handleChange={handleChange}
          formSubmit={formSubmit}
        />

        <Todos
          tasks={tasks}
          handleDelete={handleDelete}
          handleDeleteAll={handleDeleteAll}
          Checked={Checked}
          tasksChechked={tasksChechked}
        />
      </div>

    </>
  )
}

export default App

I have created todo with react, all functionality is working. Add, delete, checked vs. But I don't know how to add todo in localstorage. How i can save this todo in local storage. I have to files : Form.jsx and Todos.jsx. My input and button in Form, todos items (li) in Todos.jsx I have created todo with react, all functionality is working. Add, delete, checked vs. But I don't know how to add todo in localstorage. How i can save this todo in local storage. I have to files : Form.jsx and Todos.jsx. My input and button in Form, todos items (li) in Todos.jsx

import React from 'react'
const Form = (props) => {

    const { inputValue, handleChange, formSubmit } = props;

    return (
        <>
            <div className="todo-form" >
                <div className="todo-header">
                    <h1>TODO</h1>
                </div>
                <form className="todo-main" onSubmit={formSubmit}>
                    <input
                        type="text"
                        id='todo-input'
                        value={inputValue}
                        onChange={handleChange}
                        placeholder='Tapşırığı daxil edin' />
                    <button
                        type='submit'
                        id='todo-btn'>
                        <i ></i>
                    </button>
                </form>
            </div>
        </>
    )
}

export default Form

CodePudding user response:

This will involve first saving the todos whenever there is a change. One place this might be done is in a useEffect() call with dependency array [tasks]. This can be done in places other than a useEffect but for now, let's try:

In App.js

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

Next, we also need to load stored todos when the app is reloaded. This can be done at the time when the component mounts. Again we can use useEffect() with an empty dependencies array.

In App.js

useEffect(() => {
   localStorage.getItem("todos", setTasks(JSON.parse(tasks)));
}, []);

Now coming back to the storing part. Arguably, it is best to set them in localStorage at the time you update the state, rather than listening to state changes using an effect. For this, you can simply find every usage of setTasks() and set the localStorage too. But this is done at multiple places e.g. during form submit, delete, etc. So there is a bit of code repetition this way.

CodePudding user response:

import React from 'react'
import { useState, useEffect } from 'react'
import Form from './components/Form'
import Todos from './components/Todos'
import { ToastContainer, toast } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';


const App = () => {

  

  
 const [tasks, setTasks] = useState([
    {
      task: "ES 6 standartlarını öyrənmək ",
      completed: false
    },
    {
      task: "filter(), find() funksiyalarının fərqini öyrənmək",
      completed: false
    },
    {
      task: "İngilis dilində 1000 söz əzbərləmək",
      completed: true
    },
    {
      task: "Yeni framework öyrənmək",
      completed: false
    },
    {
      task: "Evə çörək almaq",
      completed: false
    }
  ]);



  const [inputValue, setInputValue] = useState('');

  const [tasksChechked, setTasksChechked] = useState(0);

  useEffect(() => { setTasksChechked(tasks.filter(task => task.completed).length) });

  const handleChange = (e) => {
    setInputValue(e.target.value);
  }

  const formSubmit = (e) => {
    e.preventDefault();
    if (inputValue !== '') {
      const newTask = {
        task: inputValue,
        completed: false,
      }
      setTasks([...tasks, newTask])
      setInputValue('')
let myTask = tasks.push(newTask)
window.localStorage.setItem('myTasks',JSON.stringify(myTask))
      toast.success("Tapşırıq uğurla əlavə edildi");
    }
    else {
      toast.error("Zəhmət olmasa tapşırığı daxil edin");
    }
  }

  const handleDelete = (index) => {
    const newTasks = [...tasks]
    newTasks.splice(index, 1)
    setTasks(newTasks)
let myTask = tasks.push(newTask)
window.localStorage.setItem('myTasks',JSON.stringify(newTasks))
    toast.error("Tapşırıq  silindi")

  }

  const handleDeleteAll = () => {
    setTasks([])
window.localStorage.setItem('myTasks','')
    toast("Bütün tapşırıqlar  silindi");

  }

  const Checked = (index) => {
    const newTasks = [...tasks];
    newTasks[index].completed = !newTasks[index].completed;
    setTasks(newTasks);
window.localStorage.setItem('myTasks',JSON.stringify(newTasks))
  }
//for load data from local storage
useEffect(()=>{
let myLocalTasks = JSON.parse(window.localStorage.getItem('myTasks'))
setTasks(myLocalTasks);
},[])
  return (
    <>
      <div className="content">
        <Form
          inputValue={inputValue}
          handleChange={handleChange}
          formSubmit={formSubmit}
        />

        <Todos
          tasks={tasks}
          handleDelete={handleDelete}
          handleDeleteAll={handleDeleteAll}
          Checked={Checked}
          tasksChechked={tasksChechked}
        />
      </div>

    </>
  )
}

export default App
// anything goes wrong please let me know
  • Related