I am new to React and am having an issue trying to render my component. It is a select component that will show a list of hospitals. It uses an axios get request to obtain the data. When trying to use the .map function, the console displays the "hospitals.map is not a function" error.
Here's the code:
import ReactDOM from "react-dom";
import { FaSearch, FaArrowDown } from "react-icons/fa";
import React, { useEffect, useState } from "react";
import {
Container,
Col,
Form,
FormGroup,
Label,
Input,
Button,
Row,
} from "reactstrap";
import "./App.css";
function Hospitals( ){
const [hospitals, setHospitals] = useState("")
useEffect(() => {
const fetchHospitals = async () => {
const result = await axios(
'/search',
);
setHospitals(result.data);
};
fetchHospitals();
}, []);
return (
<Container className="formcontainer">
<h2>
Pay Less for Healthcare Services! Start Here
</h2>
<Form className="form">
<Col>
<FormGroup>
<Input
type="select"
onChange = {e => setHospitals(e.target.value)}
value={hospitals}
>
{hospitals.map((hospital) =>
<option
key={hospital.id}
value= {hospital.hospital_name}
> {hospital.hospital_name} </option>
)}
</Input>
</FormGroup>
</Col>
<Button>
Search <FaSearch />
</Button>
</Form>
</Container>
)
}
export default Hospitals
Any help or suggestions are greatly appreciated.
console.log(result.data)in your useEffect hook? Also you should probably move thefetchHospitalsfunction declaration out of that hook.const [hospitals, setHospitals] = useState("")- you've initially declaredhospitalsas an empty string, change it to an empty array[]