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
import {
BrowserRouter as Router,
Switch,
Route,
Link
} from "react-router-dom";
import axios, { Axios } from "axios"
import { useState, useEffect } from "react";
import '../index.css'
function SearchResults() {
const [searchValues, setSearchValues] = useState({})
useEffect(() => {
receivedata();
}, [searchValues])
const receivedata = async () => {
await axios.get('http://localhost:3001/getresults').then((response) => {
setSearchValues(response.data)
console.log(searchValues);
console.log("holaaaa")
console.log(searchValues.length)
}).catch(err => {
console.log(err)
console.log("i am here")
})
}
return (
<SearchDisplay></SearchDisplay>
);
function SearchDisplay() {
return (
<div>
{ searchValues.length !== 0 || typeof searchValues != undefined ? searchValues.map(flight => {
return <div className="flights">
<ul >
<li>Flight Number : {flight.FlightNumber} </li>
<li>Arrival Time : {flight.ArrivalTime} </li>
<li> Departue Date : {flight.DepartureDate} </li>
<li> Arrival Terminal : {flight.ArrivalTerminal} </li>
<li> Departure Terminal : {flight.DepartureTerminal} </li>
<li> Economy Seats : {flight.EconomySeats}</li>
<li> Business Class Seats : {flight.BusinessClassSeats}</li>
<li>Airport : {flight.Airport}</li>
<li>Arrival Terminal : {flight.ArrivalTerminal}</li>
</ul>
</div>
}) : <h1>No Results Found</h1>
}
</div>
)
}
}
export default SearchResults;
This is the Code of the Component
CodePudding user response:
Change
const [searchValues, setSearchValues] = useState({})
to
const [searchValues, setSearchValues] = useState([])
You were not setting the state to be an array on load