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

Time:07-03

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;

CodePudding user response:

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('');
};

CodePudding user response:

You need to create a state using useState so that when you update the state then React will re-render the component

const [myTaskList, setMyTaskList] = useState( [] );

CODESANDBOX LINK

Since you are using form here so you also have to preventDefault

  const handleSubmit = ( e ) => {
    e.preventDefault();  // CHANGE
    setMyTaskList( ( oldTask ) => {   // CHANGE
      return [
        ...oldTask,
        {
          id: Math.floor( Math.random() * 10000 ),
          text: task,
        }
      ];
    } );
    setTask( '' );
    console.log( myTaskList.length );
  };

You can also do as:

  const handleSubmit = (e) => {
    e.preventDefault();
    setMyTaskList([  // CHANGE
      ...myTaskList,
      {
        id: Math.floor(Math.random() * 10000),
        text: task
      }
    ]);
    setTask("");
    console.log(myTaskList.length);
  };

CodePudding user response:

Several issues in your code.

  1. you did not use useState in your taskList
  2. You did not call preventDefault()

Heres mine:

import React, { useState } from 'react';

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

// 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) => {
  e.preventDefault()
  // setMyTaskList.push({
  //   id: Math.floor(Math.random() * 10000),
  //   text: task,
  // });
  setMyTaskList(arry=>[...arry, {
    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>{myTaskList.length > 0 ? myTaskList.map((eachTask) => {
  return <li key={eachTask.id}>{eachTask.text}</li>;
}) : <li>no tasks found</li>}</ul>
      </div>
    </center>
  </div>
);
};
export default App;
  • Related