React isn't updating the on-change value despite changes being made

In my React application, there is a file called EditTodos.js that is responsible for updating the to-do list. When I click on the "Edit" button, it triggers a pop-up modal component.

import React, { useState } from "react";
import { Button, Modal } from "react-bootstrap";

export default function EditTodo({ todo }) {
  const [description, setDescription] = useState(todo.description);
  const [show, setShow] = useState(false);

  const handleClose = () => setShow(false);
  const handleShow = () => setShow(true);

  const updateDescription = async () => {
    try {
      const body = { description };
      const update = fetch(`http://localhost:3000/${todo.todo_id}`, {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(body),
      });
    } catch (error) {
      console.log(error.message);
    }
  };
  return (
    <>
      <Button
        variant="warning"
        onClick={handleShow}
        data-target={`#id${todo.todo_id}`}
      >
        Edit
      </Button>

      <Modal show={show} onHide={handleClose} id={`id${todo.todo_id}`}>
        <Modal.Header closeButton>
          <Modal.Title>Edit Todo</Modal.Title>
        </Modal.Header>
        <Modal.Body>
          <input
            type="text"
            className="form-control"
            value={todo.description}
            onChange={(e) => setDescription(e.target.value)}
          />
        </Modal.Body>
        <Modal.Footer>
          <Button variant="secondary" onClick={handleClose}>
            Close
          </Button>
          <Button variant="primary" onClick={handleClose}>
            Save Changes
          </Button>
        </Modal.Footer>
      </Modal>
    </>
  );
}

I am currently experiencing an issue where I'm unable to change the value of the input field.

I've tried using

onChange={(e) => setDescription(e.target.value)}
, but it's still not working. What could be causing this problem?

Please assist me in figuring out what might be going wrong here.

Answer №1

It is not recommended to use props to define state as it leads to having two separate sources of truth for the data. Instead, the onChange function should be passed from the parent component.

          <input
            type="text"
            className="form-control"
            value={description}
            onChange={(e) => setDescription(e.target.value)}
          />

The issue with the current implementation is that the description state is updated in the onChange event, but the value always remains as description.toDo, which is received from the parent component.

However, it is advisable to avoid this pattern and maintain a single source of truth by passing the onChange function as a prop.

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

Tips for implementing both an onChange and onSubmit event for a MUI TextField

I'm currently working with React and MUI and have created a form like the following: const handleUserInput = (event) => { set_user_input(event) } const handleSubmitForm = () => { if (user_input == 'help'){ ...

Including a label for an array within an unnamed array in a JSON string

Is there a way to transform the following data: [{"name": "Donald"}, {"name": "George"}] Into this format instead: {MyArray: [{"name": "Donald"}, {"name": "George"}]} I am currently working on a database server that I built using node.js, express, an ...

Adjust the CSS to ensure that all elements have the height of the tallest element in the set

Can anyone help me solve a design issue I'm facing? I have a div with three floating buttons, but one of the buttons is taller than the others due to more content. I'm looking for a way to ensure that all buttons are the same height as the talle ...

Refresh the datatable using updated aaData

How do I automatically update the Datatable with new Json data? POST request is used to receive data, which is then sent to the LoadTable function in order to populate the datatable. function initializeTable(){ $("#submitbutton").on( 'click', ...

Can you provide a guide on how to retrieve an HTML file using JSON?

There is a problem with fetching files in different formats. Specifically, I want to retrieve an HTML file that needs to be embedded in an iFrame. Currently, my AJAX request only retrieves SWF files. Is there a way to call and fetch the HTML file instead ...

Converting dynamic content within a div into an interactive link

I am currently working with Longtail's JW Player and facing some difficulties with a basic function. Since I am not familiar with the programming language terminologies, I will describe the issue step by step: There is a JavaScript code that displays ...

What is the best way to retrieve the value of an input field in React when incorporating Material UI components?

I am working with a few radio input components that have been imported from material Ui react. Each radio input is wrapped in a FormControlLabel component. <FormControlLabel onClick={checkAnswerHandler} value={answer} control={<Radio color=&quo ...

What is the best way to initiate the handling of newly inserted values in a Vuex store?

I am working with a Vuex store that stores entries: const store = createStore({ state() { return { entries: [ { id: 1, date-of-birth: "2020-10-15T14:48:00.000Z", name: "Tom", }, ...

What is the best way to unselect the "all" selector if one of the inputs is no longer selected?

I am facing an issue with a search filter functionality. When all filters are selected and then deselected individually or together, the "all" button remains selected. I need help in ensuring that when any filter is deselected, the "all" button also gets d ...

The makeStyles function is unable to interact with dynamic CSS variables

const customStyles = makeStyles({ box: { color: "var(--custom-text) !important", }, }) The CSS variable var(--custom-text) is dynamically changing within the application based on a user toggle. However, the component utilizing this custo ...

Concealing Vimeo's controls and substituting them with a play/pause toggle button

I'm currently working on implementing the techniques demonstrated in this tutorial (), but unfortunately the code in the fiddle I put together doesn't appear to be functioning correctly. I'm at a loss as to what might be causing this issue. ...

Tips for enabling button clickability while MuI Dropdown is displayed

I'm new to using MUI and I recently utilized a code snippet like this: <Select name="premiumUser" value={1} displayEmpty={true} fullWidth> <MenuItem value={1}>True</MenuItem> <MenuItem value={2}>False</Menu ...

JSON Date Format

I'm facing an issue where I am unable to retrieve the current date using new Date() because it is in JSON format. This particular code was written using MVC C#. The date appears as \/Date(1531364413000)\/. The dates stored in the database ...

What causes useEffect to trigger twice when an extra condition is included?

Attempting to create a countdown timer, but encountering an interesting issue... This code triggers twice in a row, causing the useEffect function to run twice per second. 'use client' import {useState, useEffect, useRef} from 'react' ...

The React Vite application encountered an issue: There is no loader configured for ".html" files at ../server/node_modules/@mapbox/node-pre-gyp/lib/util/nw-pre-gyp/index.html

**Encountered errors in a React Vite web app** ** ✘ [ERROR] No loader is configured for ".html" files: ../server/node_modules/@mapbox/node-pre-gyp/lib/util/nw-pre-gyp/index.html ../server/node_modules/@mapbox/node-pre-gyp/lib/node-pre-gyp.js:86 ...

How can I change the nested Material UI component style from its parent component?

I am currently incorporating a component from an external library into my project. However, I am facing limitations in customizing its style, especially when it comes to a button that is using material ui styles. Upon inspecting the element, I can see that ...

The toggle class feature of jQuery is malfunctioning when placed inside a different div

Hello everyone, I am currently working on a toggle effect on my webpage. However, I encountered an error when trying to move the button close to another part of the page. The button works fine if it is placed in one part of the HTML, but does not work if i ...

The alignment of inline-block elements is not being maintained on the same line

Here's a question I have about my embedded form. Why does the display property of inline-block make the "submit" and "terms" elements appear higher than the email field? And more importantly, how can I fix this issue? I've attempted to use the t ...

Troubleshooting: Issue with AngularJS Image onload directive - "this" reference not functioning properly?

I have a custom directive that looks like this: .directive('ngImageOnLoad', function () { return { restrict: 'A', link: function(scope, element, attrs) { element.bind('load', function() { ...

Utilize flexbox to create a list that is displayed in a column-reverse layout

I am facing a challenge in displaying the latest chat person in the 1st position (active) using Firebase. Unfortunately, Firebase does not have a date field which makes it difficult to achieve this. I have attempted converting the date into milliseconds an ...