Home > database >  TypeError: Cannot read properties of undefined (reading 'map') Trying to Read REST api and
TypeError: Cannot read properties of undefined (reading 'map') Trying to Read REST api and

Time:11-17

This is the JSON content gotten from the REST api i am querying

{
    "DataLength": 1,
    "Data": [
        {
            "_id": "619248d9632a4d022bf10b14",
            "email": "********@*******.***",
            "name": "",
            "contactNo": "12345676890",
            "activeStatus": true,
            "leadSource": "Website",
            "leadPerson": [
                "618cdc9f440a5c641e0a273b"
            ],
            "customerLeadId": [
                "61921f1faa24f6068ea5ef36"
            ],
            "estimaitonDate": "",
            "estimaitonSentDate": "",
            "estimaitonStatus": "Process",
            "leadInvoinceNo": "E1000003",
            "createdAt": "2021-11-15T11:47:37.300Z",
            "updatedAt": "2021-11-15T11:47:37.300Z",
            "__v": 0
        }
    ]
}

Now i am trying to put the information into HTML in react to show the information. I used UseEffect and useState to get the information from the REST api.

i used useState like this const [posts, setCustomerData] = useState(); And in the useEffect I do something like this

useEffect(()=>{
    let token = localStorage.getItem('token');
    fetch('url',{
        method: 'GET',
        mode:'cors',
        headers:{
            'Accept': 'application/json',
            'Content-Type': 'application/json',
            'Authorization': 'Bearer ' token,
        },
    }).then((response)=>response.json())
    .then((responseJson)=>{
        setCustomerData(responseJson.Data);
    })
},[])

and putting into the HTML

    <div className="TablesCustomerWhiteBg__">
        <img src={vis} className="whiteBg__" />
        <input type="button" onClick={toggleModal} value="Add Column" className="AddColumn__" /><span><input type="text" placeholder="  &#xF002;    Search customer by name" className="SearchBox__" /></span>
    </div>
    <div className="dataTableInfos__">
        {posts.map(post=>(                              //starts here 
        <table className="displayTableInfos__">
            <tr>
                <th>Estimate #</th>
                <th>Customer Name</th>
                <th>Software Followup</th>
                <th>Status</th>
                <th>Estimate Date</th>
            </tr>
            <tr>
                <td align="center">{post.id}</td>
                <td align="center">{post.name}</td>
                <td align="center">mmm</td>
                <td align="center">{post.estimaitonStatus}</td>
                <td align="center">{post.estimaitonDate}</td>
            </tr>

        </table>
        ))}                                     //ends here
    </div>

This is the Error i am getting.

×
TypeError: Cannot read properties of undefined (reading 'map')
DashBoard
D:/react/FrontEnd/src/DashBoard.js:129
  126 |     <img src={vis} className="whiteBg__" />
  127 |     <input type="button" onClick={toggleModal} value="Add Column" className="AddColumn__" /><span><input type="text" placeholder="  &#xF002;    Search customer by name" className="SearchBox__" /></span>
  128 | </div>
> 129 | <div className="dataTableInfos__">
      | ^  130 |     {posts.map(post=>(
  131 |     <table className="displayTableInfos__">
  132 |         <tr>
View compiled
▶ 19 stack frames were collapsed.
(anonymous function)
D:/react/modules/Router.js:34
  31 | if (!props.staticContext) {
  32 |   this.unlisten = props.history.listen(location => {
  33 |     if (this._isMounted) {
> 34 |       this.setState({ location });
     | ^  35 |     } else {
  36 |       this._pendingLocation = location;
  37 |     }
View compiled
▶ 7 stack frames were collapsed.
(anonymous function)
D:/react/FrontEnd/src/HomePage.js:32
  29 |     //alert(token);
  30 |     localStorage.setItem('userinfo', email);
  31 |     localStorage.setItem('token', token);
> 32 |     history.push('/dashboard');
     | ^  33 | }else{
  34 |     alert(responseJson.error);
  35 | }
View compiled
This screen is visible only in development. It will not appear if the app crashes in production.
Open your browser’s developer console to further inspect this error.  Click the 'X' or hit ESC to dismiss this message.

Please I need help here of some sort, How do I resolve this? Why am I getting this Error?

CodePudding user response:

if you look at the code .useEffect is called after first render.when first render appear it get undefined data from your useState. Solution 1:Default the Variable to an Empty Array

change this // [posts, setCustomerData] = useState()

to this

[posts, setCustomerData] = useState([])

if problem persists. then try to use Different names for your API data and useState for map. 2

  • Related