How to change specific item on state of array in React?

Viewed 79

I am creating a todolist with react and context API. As a default, when item is created "isDone" key of array item is false. When I click the completeAll button, I want to make all task's "isDone" true.

import './FormInput.scss';
import List from '../List/List';
import Footer from '../Footer/Footer';
import {MainContext, useContext} from "../../context";

function FormInput() {

   const {taskList, SetTaskList} = useContext(MainContext);

   const submitTask = (e) => {
     e.preventDefault();
     SetTaskList((prev) => [...prev,{"task":e.target.task.value,"isDone":false}])
     console.log(e.target.task.value);
    }

   const CompleteAll = (e) =>{
       SetTaskList((prev) => {
        const list = prev.map((item) => item.isDone===true)
        return{
           list
         }
    })
   }
   return (
    <div className="form-input">
      <h1>TODOS</h1>
     <div className="form-top">
      <button id="completeAll" onClick = { e => CompleteAll(e)}>❯</button>
      <form onSubmit = {(e) => submitTask(e)}>
        <input type="text" name="task" id="taskInfo" placeholder="What needs to be done?"/>
      </form>  
    </div>
    <List/>
     { taskList[0] ? <Footer/> : ""}
    </div>
   );
  }

  export default FormInput;

Here is the code. I try to code completeAll function but it set the tasklist to a single true, false value.

1 Answers

You can use spread operator to do it.

const CompleteAll = (e) => {
  SetTaskList((prev) => {
    return prev.map((item) => ({ ...item, isDone: true }));
  });
};
Related