Home > Back-end >  React: Update a specific attribute of an array of objects
React: Update a specific attribute of an array of objects

Time:05-31

I have a rather simple requirement which is turning out to be quite complex for me. I'm developing a basic todo app with following UI:

Design

Now I need to update the array of object such that only the text of specific item should be updated. Here is my attempt but it just adds a new component on every key press:

import React, {useState} from "react";

const DynamicInput = () => {
  const [todos, setTodos] = useState([])
  
  
  const onAddClick = () => {
    setTodos(prevState => {
      return [...prevState, {id: prevState.length   1, text: "", up: "↑", down: "↓", del: "x"}]
    })
  }
  
  const onValueUpdate = (id) => (event) => {
    let tempObject = todos[id]
    
    setTodos(prevState => {
    return [...prevState, {
        id: id,
        text: event.target.value,
        up: "Up",
        down: "Down",
        del: "x"
        }];  
    })

  }
  
  const onUpArrow = (event) => {
    console.log("On up")
  }
  
  const onDownArrow = (event) => {
    console.log("On down")
  }
  
  const onDeleteArrow = (event) => {
    console.log("On delete")
  }
  
  return (
    <>
      <button onClick={onAddClick}> </button>
      {todos.map(todo => {
        return( 
          <div key={todo.id}>
            <input onChange={onValueUpdate(todo.id)} value={todo.text}></input>
            <button onClick={onUpArrow}>{todo.up}</button>
            <button onClick={onDownArrow}>{todo.down}</button>
            <button onClick={onDeleteArrow}>{todo.del}</button>
          </div>)
      })}
    </>
  );
};
export default DynamicInput;

CodePudding user response:

To simply solve your problem you can change your onValueUpdate() method to this :

const onValueUpdate = (id) => (event) => {
    setTodos(prevState => {
        let data = [...prevState];
        let indexOfTodo = data.findIndex(todo => todo.id === id);
        data[indexOfTodo] = {
            ...data[indexOfTodo],
            text: event.target.value,
        };
        return data;
    });
};

  • Related