0

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.

2
  • What do you see if you console.log(result.data) in your useEffect hook? Also you should probably move the fetchHospitals function declaration out of that hook. Commented Apr 19, 2021 at 20:32
  • 1
    const [hospitals, setHospitals] = useState("") - you've initially declared hospitals as an empty string, change it to an empty array [] Commented Apr 19, 2021 at 20:33

1 Answer 1

3

The .map() function only works for arrays. So hospitals should be an array. I think

const [hospitals, setHospitals] = useState([]);

will do it for you.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.