Home > Back-end >  Only the last element is displayed in the tasks array react
Only the last element is displayed in the tasks array react

Time:07-08

If I comment out the code //setTasks([task]), then everything is ok.

I note that the tasks array changes without problems after changing the fields

I think the solution here is very simple, you need to call the setPosts function correctly by converting the "old" array, replacing one element with a "new" element from

<PageTasks.jsx>

    const PageTasks = () => {

    const [tasks, setTasks] = useState([
    {
      id: 1,
      nameTask: 'Продукты',
      descriptionTask: 'Масло',
    },
    {
      id: 2,
      nameTask: 'д/з',
      descriptionTask: 'Сделать д/з',
    },
    {
      id: 3,
      nameTask: 'Перестановка',
      descriptionTask: 'Помочь бабушке сделать перестановку',
    }
    ])

    function changeTask(task){
      setTasks([task])
    }

    return(

    <Tasks
        setTasks={changeTask}
        tasks={tasks}
     />
    )
    export PageTasks;

<Tasks.jsx>

    const Tasks = ({ tasks, setTasks }) => {

    return(
     {
         tasks.map((task) =>
              <Task
                 setTasks={setTasks}
                 key={task.id}
                 task={task}
               />
            )}
    )
    export Tasks;

<Task.jsx>

    const Task = ({ task, setTasks }) => {
    
    const [taskEdit, setTaskEdit] = useState(task)
    
    useEffect(()=>{
        setTasks(taskEdit)
    },[taskEdit])

    return (
      <MyInput
          value={taskEdit.nameTask}
          onChange={e => setTaskEdit({ ...taskEdit, nameTask: e.target.value })}
      />
      <MyInput
         value={taskEdit.descriptionTask}
         onChange={e => setTaskEdit({ ...taskEdit, descriptionTask: e.target.value })}
      />
    )
    };
    export default Task;

CodePudding user response:

You are setting your tasks array to be the last task element. What you need to do is update your tasks array with this latest element.

function changeTask(task){
   const index = tasks.findIndex(tsk => {
     return tsk.id === task.id
   })

  setTasks(Object.assign([ ...tasks ], { [index]: task })
}
  • Related