iLoveSpicyNoodles
iLoveSpicyNoodles

Reputation: 102

TypeError: .map is not a function

I'am making a little To-Do app to learn more about ReactJS and React Hooks. The problem is that i don't understand what is wrong with the list.map() that i'am using. It keeps telling me that its not a function. But i don't see how im using it as a function in the first place?

I have been look all over google to see what i'm doing wrong. i have tried changing my code in multiple ways but i can't seem to figure out what is wrong. As soon as i click my "Submit" button, it crashes and gives me the TypeError: list.map is not a function error.

function ToDoList() {
  const [list, setlist] = useState(["Test 1", "Test 2"]);
  const [newItem, setnewItem] = useState("");

  const handleChange = e => {
    setnewItem(e.target.value);
    console.log(newItem);
  };

  const handleSubmit = () => {
    setlist(...list, newItem);
  };

  return (
    <div>
      <input onChange={handleChange} />
      <button onClick={handleSubmit}>Submit</button>
      <ul>
        {list.map((item, index) => (
          <li key={index}>{item}</li>
        ))}
      </ul>
    </div>
  );
}

function App() {
  return (
    <div className="App">
      <AppTitle />
      <ToDoList />
    </div>
  );
}

I'am trying to add the newItem to the list and render the list through .map(). When i start the app, the "Test 1" and "Test 2" Render, but adding to the list and rerendering it crashes it.

Upvotes: 3

Views: 29483

Answers (1)

Dacre Denny
Dacre Denny

Reputation: 30390

The reason for this runtime error is that handleSubmit() is updating the list state to a non-array type:

  const handleSubmit = () => {
    /* 
    The list is spread into the arguments of setlist() meaning that state
    is updated to the first value of the list array
    */ 
    setlist(...list, newItem);
  };

When handleSubmit() is therefore called, the list state value is no longer an array which in turn means that list.map() no longer defined, hence the error:

".map() is not a function".

If you change the following section of code in your component, this will ensure that list is updated as a new array (where the value of "newItem" is appended to the end of that new array):

  const handleSubmit = () => {

    /* 
    Update the list state to a new array, with newItem appended to the
    end of it. This ensures the list state remains as an array type,
    ensuring the list.map() is defined 
    */
    setlist([...list, newItem]);
  };

Upvotes: 11

Related Questions