Issue with the Edit feature causing conflicts with the local storage and generating error messages

There seems to be an issue with my edit function that is causing it to override the local storage when I attempt to save and interfering with my delete function as well. I have searched through similar posts for a solution but have not been able to pinpoint the problem. For the full code, you can refer to my GitHub repository: https://github.com/ottowoolf/NotesApp.

import React, { useState, useEffect } from "react";
import { Form, Container, Button } from "react-bootstrap";
import { useParams } from "react-router-dom";

export const Edit = ({ notes, setNotes }) => {
  const [form, setForm] = useState({
    title: "",
    text: "",
    id: "",
  });
  const { id } = useParams();

  useEffect(() => {
    let index = notes.find((n) => n.id === id);
    let selectedNote = notes[index];
    console.log(notes[index]);
    console.log(id);
    console.log(selectedNote);
    setForm(selectedNote);
  }, [id, notes]);

  const handleChange = (e) => {
    const { value, name } = e.target;
    setForm({ ...form, [name]: value, id });
    console.log(form);
  };

  const saveNote = () => {
    if (form.title.trim() !== "" || form.text.trim() !== "") {
      setNotes((note) => {
        // return array - with the object of /id/ modified
        let index = note.find((n) => n.id === id);
        let newNotes = [...note];
        newNotes[index] = form;
        console.log(newNotes[index]);
        return newNotes[index];
      });
    }
  };

  return (
    <React.Fragment>
      <Container>
        <Form className='mt-3 w-50'>
          <Form.Group controlId='formBasicEmail'>
            <Form.Control
              onChange={handleChange}
              value={form.title}
              name='title'
              type='text'
            />
          </Form.Group>

          <Form.Group controlId='formBasicPassword'>
            <Form.Control
              onChange={handleChange}
              value={form.text}
              name='text'
              as='textarea'
              cols='30'
              rows='10'
            />
          </Form.Group>
        </Form>
        <Button onClick={saveNote} className='btn btn-success'>
          Save
        </Button>
      </Container>
    </React.Fragment>
  );
};

Answer №1

I've made some changes to your GitHub repository and updated it using codesandbox.

Feel free to check out the link here: https://codesandbox.io/s/aged-dawn-bnv6v?file=/src/pages/Edit.js

Please let me know if there's anything else you'd like me to add or adjust.

Additionally, I recommend tidying up your code a bit as it appears quite extensive for a Notes App.

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

Is it advisable to incorporate vue-resource in Vuex actions?

I am currently working on a web application that retrieves airport data from the backend. To manage states and data sharing, I am utilizing Vuex. My dilemma is whether to load the airports in my Vuex actions or within a method of my Vue instance which will ...

Bot on Discord using Discord.Js that generates unique invites for users

I'm trying to find a way to generate an invite link for users to keep track of invites. The code I have currently is creating the invite for the Bot instead. const channel = client.channels.cache.find(channel => channel.id === config.server.channel ...

Displaying postcode on a category page: A step-by-step guide

I would like to showcase the user input code and present it on the web exactly as entered. <?php #code... ?> Any assistance is greatly appreciated. Please excuse my English. Thank you! ...

Converting an array of arrays into an object with an index signature: A step-by-step guide

I find myself facing a challenge where I have two types, B and A, along with an array called "a". My objective is to convert this array into type B. Type A = Array<[string, number, string]>; Type B = { [name: string]: { name: ...

Troubleshooting the Confirm Form Resubmission problem on my website

Hello everyone! I'm working on a website and facing an issue where refreshing the page triggers a confirm form resubmission prompt. Could someone please advise me on how to resolve this? Thank you in advance! ...

You are unable to move the image to the top of the screen after zooming it with CSS

I implemented an image viewer component with interactive buttons for rotating, zooming in, and zooming out. Upon clicking a button, CSS transform is applied to the image. However, I encountered an issue where, when zooming the image, it cannot be scrolled ...

Having trouble toggling between the trending and search features on giphy website

I've been developing a chat application with NextJS and I'm currently working on integrating GIPHY images into it. Although I have the basic setup in place, I'm facing issues when switching between the giphy.search() and giphy.trending() fu ...

tips for patiently awaiting an ajax response before setting the object

I am currently working on a basic todo app using React. Initially, everything was running smoothly when I stored my data in a pre-defined object. However, now that I am retrieving my data from a link (rest) using AJAX, I seem to be encountering some issues ...

What is the best way to display a child element in the right panel?

Hello, I need help in displaying child elements next to the parent element. My function works fine the first time, but fails the second time. Here are the steps I followed: 1) Clicked the Add button 2 times, generating row2 as well as a submenu of firs ...

Error handling middleware delivering a response promptly

Issue with my express application: Even after reaching the error middleware, the second middleware function is still being executed after res.json. As per the documentation: The response object (res) methods mentioned below can send a response to the cl ...

Significant delay in processing second jQuery Ajax call

Attempting a simple Ajax call with page content refresh using the following code snippet: $("a.ajaxify-watched").bind("click", function(event) { $item = $(this); $.ajax({ url: $(this).attr("href"), global: false, type: "G ...

The webpage continues to refresh after executing a JavaScript function triggered by the AJAX response

I have experimented with various solutions for calling a JavaScript function returned from an AJAX response. While each method worked to some extent, I found that using an alert within the refreshResults function was necessary in order to display the resul ...

What is preventing me from displaying an AJAX JSON value on my website?

Below is the code snippet: <ul> <li v-for="value in RandomTopic" :key="value.id">{{ value.title }}</li> </ul> export default { data() { return { RandomTopic: null } }, mounted() { ///so ...

I'm looking to implement a feature in my notes application built with the MERN stack using Mongoose for MongoDB that allows users to add hidden notes. How

I am looking to implement a hidden notes functionality in my web application. When the "hide note" button is clicked, I want the note to be removed from its current location and added to a hidden notes section. Users should then have the ability to view an ...

When trying to return a string value from array.find(), I encountered an error stating that Objects cannot be used as a React child

The code snippet below shows that console.log(el.distance) is equal to a string. Despite this, whenever I attempt to return el.distance, React throws the error: Error: Objects are not valid as a React child (found: object with keys {item, distance}). If y ...

Tips for updating a JSON object value in Node.js

Storing a JSON object in a JSON file is important for passing data during an API call. To update the object, replace "it-goes-here" with the following {} block. Newly updated data: { "parenturl":"xxx.com", "user ...

Invoking a nested method within Vue.js

I am facing an issue in my vuejs application with 2 methods. When I define method1 a certain way, it does not run as expected. method1: function(param1, param2){ // I can log param1 here thirdLib.debounce(function(param1, params2){ // It d ...

What is the best way to record data while initiating a process in node.js?

In my latest project, I have implemented a function that spawns a process and requires logging specific information to the console. Here is an example of how this function is structured: function processData(number) { var fileName = settings.file || "de ...

How can you prevent JQuery AJAX from automatically redirecting after a successful form submission?

Encountered an issue with loading http://example.com/signup.ashx: The redirect from 'http://example.com/signup.ashx' to '' was blocked by the CORS policy. This is due to the absence of 'Access-Control-Allow-Origin' header on t ...

The pagination in the DataGrid is not aligning correctly to the right when placed within a container with the "rtl" direction attribute

I'm struggling to set up a DataGrid with pagination using Material-UI within a container that has dir="rtl". Despite customizing the pagination component to align to the right side of the container, it doesn't seem to be working correctly. Take ...