Why is data.map not a function?

Viewed 1026

I built the following component in React:

import React, { useState } from 'react';


export default function Exemple(){

    var friend = function (id, firstName, lastName){
        this.id = id; this.firstName = firstName; this.lastName = lastName
    }

    var [data, setData] = useState( [
        new friend(1, 'jon', 'well')
    ])

    var newFriend =  new friend();

    function addFriend(e){  
        newFriend[e.target.id] = e.target.value;
    }

    function saveFriend(){
        setData(data.push(newFriend));
    }

    return( 
    <div className="my-table-friends">
         <table className="table">
    <thead>
      <tr>
        <th className="my-table-th">id</th>
        <th className="my-table-th">first name</th>
        <th className="my-table-th">last name</th>
      
      </tr>
    </thead>
        <tbody>
          
            {data.map((d)=>{return(
                <tr>
                    <td>{d.id}</td>
                    <td>{d.firstName}</td>
                    <td>{d.lastName}</td>
                </tr>)
            })}
        </tbody> 
  </table>

  

    <form>
    <label for="fname">id</label><br />
    <input type="text" id="id" name="fname" onChange={addFriend}/><br />
    <label for="fname">first name</label><br />
    <input type="text" id="firstName" name="fname" onChange={addFriend} /><br />
    <label for="lname">last name</label><br />
    <input type="text" id="lastName" name="lname" onChange={addFriend}/><br />
    <button onClick={saveFriend}>add</button>
    </form>
 
    </div>)
}

There is a table of friends here, and a form for adding friends. The table gets its data from the 'data' array and displays it using the map function. For some reason, when I update the array the array becomes an object, and gets an error that data.map is not a function. What is the explanation for this?

1 Answers

You're mutating the state and setting it to integer. The following is wrong:

setData(data.push(newFriend));

Instead, please do this:

function saveFriend(){
  const newData = [...data, newFriend];
  setData(newData);
}

Or in simple way:

function saveFriend(){
  setData([...data, newFriend]);
}

The reason why this doesn't work is, Array.push() returns the length of the array, thereby, setting the data to a number. And an integer doesn't have the map() function so you get the error.

Related