Ghulam Azam Khan
Ghulam Azam Khan

Reputation: 37

How to update object property in useState hook?

I want to when the user clicks submit button it should add new object. with the given value which is stored in list varaible.It should not delete the old objects,only name Property should be added.

import { useState } from "react";
export default function Add() {
  const [todo, addTodo] = useState([{ name: "cat", time: "2 minutes ago" }]);
  const [list, setList] = useState();

 
  const add = () => {
    addTodo({...todo,  todo: {
      name: list
        }})
  };

  return (
    <div>
      <input
        type="text"
        value={list}
        onChange={(e) => setList(e.target.value)}
      />
      <button onClick={add}>Add new</button>
      {todo.map((item, i) => (
        <li key={i}>
          {item.name}
          <span style={{ marginLeft: "15px" }}>{item.time}</span>
        </li>
      ))}
    </div>
  );
}

Upvotes: 1

Views: 544

Answers (2)

Viet
Viet

Reputation: 12807

Because todo is an array so you should pass an array when call addTodo

addTodo([
  ...todo,
  {
    name: list,
  },
]);

Upvotes: 0

Shyam
Shyam

Reputation: 5497

When your state update is dependent on the previous state value ,its a good practice to make the state updater to have an inline function .

addTodo(existingTodos => ([...existingTodos, { name: list}] ))

Here we are saying , get the exisitingTodos list and append the new todo along with the exisitingTodos .

const add = () => {
    addTodo(existingTodos => ([...existingTodos, { name: list}] ))
  };

Upvotes: 1

Related Questions