My attempts to utilize the local storage key have been unsuccessful in storing my todo list. I am uncertain where the issue lies within my code

I've been working on a Todo List with local storage in React, but I'm running into an issue. It seems that my todos aren't getting stored properly and are disappearing every time the page refreshes. I need to figure out what's causing this problem and how I can fix it. Here is my code:

import React, { useState, useRef, useEffect } from "react";
import TodoList from "./TodoList"

const { v4: uuidv4 } = require('uuid');
const LOCAL_STORAGE_KEY = 'todoApp.todos'


function App() {
  const [todos, setTodos] = useState([])
  const inputRef = useRef()
 
  useEffect(() => {
    const storedTodos = JSON.parse (localStorage.getItem(LOCAL_STORAGE_KEY))
    if (storedTodos) setTodos(storedTodos)
  }, [])

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


  function toggleTodo(id){
    const updatedTodos = [...todos]
    const todo = updatedTodos.find(todo=> todo.id === id)
    todo.complete =!todo.complete
    setTodos(updatedTodos)
  }
    
    
  

  function handleAddTodo(e){
    const name = inputRef.current.value
    if (name === '') return
    setTodos(prevTodos =>{
      return [...prevTodos, {id: uuidv4(), name: name, complete: false}]
    })
  }



  return (
    <>
    <TodoList todos={todos} toggleTodo={toggleTodo}/>
    <input ref={inputRef} type="text" />
    <button onClick={handleAddTodo}>Add Todo</button>
    <button>Clear Todo</button>
    <div>0 Todos Left</div>
    </>
  )
}
export default App;

Answer №1

Simply hit the refresh button to see all the updates take effect.

Click here

Answer №2

useEffect in React will run when the component mounts and whenever there are changes to the specified variables in []. In your current code,

localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(todos))
is executed at component mount before todos is set by the first useEffect.

To better understand, add a console.log as shown below:

useEffect(() => {
  localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(todos));
  console.log("setting", todos);
}, [todos]);

Solution:

To resolve the issue, remove the existing useEffect and set the local storage in the function where the todos state is updated.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountering issues with Office.context.document.getFileAsync function

I am experiencing a strange issue where, on the third attempt to extract a word document as a compressed file for processing in my MS Word Task Pane MVC app, it crashes. Here is the snippet of code: Office.context.document.getFileAsync(Office.FileType.Co ...

Display the current page as it appears in AngularJS

I attempted to utilize the ngPrint directive from https://github.com/gilf/ngPrint for printing purposes. However, when I print the page, the design collapses entirely. Is there a solution to maintain the page layout when printing? Please note that Angula ...

Webpack with Linaria is currently not enabled to support the experimental syntax 'jsx'

I've recently integrated linaria into my webpack configuration for a create-react-app project. Here is the resulting rule: { "test": /\.(js|mjs|jsx|ts|tsx)$/, "include": "C:\\Project\\src", ...

Troubleshooting URL Problems with Node.js Search and Pagination

My results page has pagination set up and the routes are structured like this: app.get("/results",function(req,res){ query= select * from courses where // this part adds search parameters from req.query to the sql query// Object.keys(req.query.search).for ...

What is the best way to incorporate messages across various channels with a Discord bot?

While browsing through the questions of other users, I stumbled upon exactly what I was looking for. My dilemma now is how to make the same bot perform similar tasks on various channels but with different titles, footers, and so on... The primary code sni ...

Top method for utilizing render props in React

Currently, I am employing render model props. However, I have a hunch that there might be an alternative method to achieve the same outcome. Is anyone familiar with another approach? {variable === "nameComponen" && <component/>} {variable === "name ...

Mastering MongoDB update functions in JavaScript

I've encountered some difficulties while using the MongoDB API to update a document. Despite trying various methods, none of them have been successful so far. Strangely enough, inserting and deleting documents work perfectly fine. Let me explain what ...

Use JavaScript to sift through an array and exclusively retrieve items that match a specific value

I am working with an array of objects that contain a phase key, and I want to filter out only the ones that have a specific phase value. Additionally, I need to map some other key/value pairs into the final return. Here is my current code: phaseToBlocks ( ...

How to showcase information stored in Firebase Realtime Database within an Ionic application

Looking to list all children of "Requests" from my firebase realtime database in a structured format. Here's a snapshot of how the database is organized: https://i.stack.imgur.com/5fKQP.png I have successfully fetched the data from Firebase as JSON: ...

Is it possible to direct the focus to a specific HTML element when the tab key is pressed?

Seeking a solution to shift focus to a button once the user presses the tab key from the currently selected control, while bypassing other dynamic controls in between. The order of controls is as follows: <dynamic drop down control 1> <dynamic d ...

Parsing JSON data on the client side in an ASP.NET application

I am currently working with JSON data that looks like this: "Table":[ { "AF":2000.00 "RegionNumber":1 "RegionName":"Black Sea" }, { "AF":100.00 "RegionNumber":1 "RegionName":"Black Sea" }, { "AF":15000.00 "RegionNumber":2 "RegionName":"Ista ...

Animation that increments to a predetermined value

I'm trying to create a counter animation that dynamically animates a value calculated by the checkboxes selected. The calculation is working fine, but the animation is not happening. http://jsfiddle.net/dbtj93kL/ $('input[type="checkbox"]&apo ...

The settimeout function does not seem to function properly within the context of

Currently, I am facing an issue with implementing block UI for blocking a specific div when a button is clicked. The problem I am encountering is that even though I want the blocked div to be unblocked after a certain delay, it remains permanently blocked ...

JavaScript code does not seem to be functioning properly on my computer, but it works perfectly fine on

While the code functions perfectly in JSFiddle, it seems to fail when I try to implement it in an HTML file. Despite my efforts, I am unable to pinpoint the source of the issue. If you'd like to view the working version, here is the Fiddle demo. Bel ...

What is the best way to instantiate a dynamic object within a literal?

I am dealing with an object that contains multiple fields, mainly consisting of constant string values. However, I also need to incorporate a variable that is determined by the current state. const {order} = this.state; myObject={{ fieldA: 2, fiel ...

I am attempting to retrieve JSON data in JavaScript but am seeing a null response in the action class

Having an issue with JSON data being sent through AJAX from the client side. The data is showing as null inside my action class. Here is the JSON string: {"data":[{"id":"","col":1,"row":1,"size_x":1,"size_y":1}, {"id":"","col":1,"row":2,"size_x" ...

When attempting to refresh the page, React Redux toolkit encounters a failure

Upon clicking a link to navigate to the profile page, the component effectively triggers actions to set the user's profile and repository. These details are then successfully retrieved using useSelector. However, upon refreshing the page, the compone ...

Error: SyntaxError - Issue with the AJAX request

When attempting to retrieve the HTML of a page using the following ajax request: $.ajax({ type: 'GET', dataType:"jsonp", url: link, success: function(response){console.log(response)}, ...

Could there be an issue with the way I've implemented my setInterval function?

I am currently in the process of developing a stopwatch feature using React Native and implementing the setInterval function to increase a counter and update the state accordingly: Play Function (triggered upon pressing the play button) const [isRunning ...

How can I pass the content of a pug input element to a JavaScript function?

Attempting to manipulate data on a database using HTML buttons and encountering an issue when trying to insert data. The setup involves a Pug page called by Node Express, which generally functions well until the insertion process. Here is a snippet from th ...