Search code examples
reactjsuse-state

Please help me find out why my react component is not mapping my list in jsx correct


I am using handleChange event to set the task using setTask() then I am using handleSubmit event to push that same task into an array when I console log the task and the array length they are both correct so I know I am modifying the array , but its still not mapping correct in my Unordered List element :

import React, { useState } from 'react';

const App = () => {
  const [task, setTask] = useState('');

  const myTaskList = [];

  const allTasks = myTaskList.map((eachTask) => {
    return <li key={eachTask.id}>{eachTask.text}</li>;
  });

  const handleChange = (e) => {
    setTask(e.target.value);
    console.log(task);
    return task;
  };

  const handleSubmit = (e) => {
    myTaskList.push({
      id: Math.floor(Math.random() * 10000),
      text: task,
    });
    setTask('');
    console.log(myTaskList.length);
  };

  return (
    <div className="todo-app">
      <center>
        <h1>MONO To Do APP</h1>
        <p>Track your progress , add tasks, then mark complete when done</p>
        <div className="space"></div>
        <form onSubmit={handleSubmit}>
          <label>Enter your next task:</label>
          <br />
          <input
            onChange={handleChange}
            value={task}
            type="text"
            name="task"
            placeholder="enter a task to track your progress..."
          />
          <br />
          <button type="submit">Add</button>
        </form>
        <div className="space"></div>
        <div className="task-list">
          <h2>Your Active Tasks List</h2>
          <ul>{allTasks.length > 0 ? allTasks : <li>no tasks found</li>}</ul>
        </div>
      </center>
    </div>
  );
};
export default App;

Solution

  • You should put myTaskList in a state to make the UI update when it changes.

    const [myTaskList, setMyTaskList] = useState([])
    
    
     const handleSubmit = (e) => {
       setMyTaskList(prev => {
         const myTaskList = [...prev]
         myTaskList.push({
          id: Math.floor(Math.random() * 10000),
          text: task,
         });
         return myTaskList
       })
       
      setTask('');
    };