I am Developing MERN Stack Project. The problem is when I make the first API Call the first response is undefined and the map function gives an error ‘Map is not a function and it makes sense. the problem is i tried several approaches to prevent this from happening but it won’t work
JavaScript
x
67
67
1
import {
2
BrowserRouter as Router,
3
Switch,
4
Route,
5
Link
6
} from "react-router-dom";
7
import axios, { Axios } from "axios"
8
import { useState, useEffect } from "react";
9
import '../index.css'
10
11
function SearchResults() {
12
const [searchValues, setSearchValues] = useState({})
13
useEffect(() => {
14
receivedata();
15
}, [searchValues])
16
17
const receivedata = async () => {
18
await axios.get('http://localhost:3001/getresults').then((response) => {
19
setSearchValues(response.data)
20
console.log(searchValues);
21
console.log("holaaaa")
22
console.log(searchValues.length)
23
}).catch(err => {
24
console.log(err)
25
console.log("i am here")
26
27
})
28
}
29
30
return (
31
<SearchDisplay></SearchDisplay>
32
);
33
34
function SearchDisplay() {
35
return (
36
<div>
37
38
{ searchValues.length !== 0 || typeof searchValues != undefined ? searchValues.map(flight => {
39
return <div className="flights">
40
<ul >
41
<li>Flight Number : {flight.FlightNumber} </li>
42
<li>Arrival Time : {flight.ArrivalTime} </li>
43
<li> Departue Date : {flight.DepartureDate} </li>
44
<li> Arrival Terminal : {flight.ArrivalTerminal} </li>
45
<li> Departure Terminal : {flight.DepartureTerminal} </li>
46
<li> Economy Seats : {flight.EconomySeats}</li>
47
<li> Business Class Seats : {flight.BusinessClassSeats}</li>
48
<li>Airport : {flight.Airport}</li>
49
<li>Arrival Terminal : {flight.ArrivalTerminal}</li>
50
</ul>
51
</div>
52
53
}) : <h1>No Results Found</h1>
54
}
55
56
57
58
</div>
59
60
)
61
}
62
}
63
64
65
66
export default SearchResults;
67
This is the Code of the Component
Advertisement
Answer
Change
JavaScript
1
2
1
const [searchValues, setSearchValues] = useState({})
2
to
JavaScript
1
2
1
const [searchValues, setSearchValues] = useState([])
2
You were not setting the state to be an array on load