Home > database >  map function doesn't work after form submit (in React 18)
map function doesn't work after form submit (in React 18)

Time:10-22

please, I'm learning React (I have installed version 18, page normal works after initial load. No warning, no errors in console). I have simple form which should add new item into an array. For list or array I'm using map function with value, index.

But after submit form I got TypeError: tasks.map is not a function

TypeError: tasks.map is not a function
App
src/App.js:28:11
  25 |  <input type="text" onChange={() => setNewTask(this.event.target.value)}></input>
  26 | </form>
  27 | <ul>
> 28 |  {tasks.map((task, index) => {
     |        ^  29 |       return <li key={index}>{task.name}</li>;
  30 |  })}
  31 | </ul>
View compiled

My conde is here:

import { useState } from 'react';

function App() {
    const [newTask, setNewTask] = useState('');
    const [tasks, setTasks] = useState([
        {
            id: 1,
            name: 'Butter',
        },
        {
            id: 2,
            name: 'Milk',
        },
    ]);

    const handleSubmit = (e) => {
        e.preventDefault();
        setTasks([...tasks].push({ id: 3, name: newTask }));
    };

    return (
        <>
            <h1>Task Manager</h1>
            <form className="newtask-form" onSubmit={handleSubmit}>
                <input type="text" onChange={() => setNewTask(this.event.target.value)}></input>
            </form>
            <ul>
                {tasks.map((task, index) => {
                    return <li key={index}>{task.name}</li>;
                })}
            </ul>
        </>
    );
}

export default App;

Of course, I also know that I must always raise the id but this I want learn via self-learning.

But I cannot resolve, why tasks.map works after page load but not after form submit and add a new item into an array.

Thanks for any advice

Best regards

CodePudding user response:

Array.prototype.push does not return the new array, but the new length of the array, so you're overwriting your state with a number (which does not have a map function).

Replace

setTasks([...tasks].push({ id: 3, name: newTask }));

with

setTasks([...tasks, { id: 3, name: newTask }));
  • Related