Tony
Tony

Reputation: 77

How to fix map is not a function error in React?

I'm having an error "map" is not a function when making an API call. I just started learning react and APIs not too long ago. I tried changing the state to object and got undefined, as [].
I got map is not a function. maybe i'm missing something calling the API. Here's the code below


function Facility() {
  
  const [facility, setFacility] = useState([]);

 try {
      const fetch = await Axios.get(
        //API
      )
      //setFacility(fetch.data);
    console.log('result', fetch.data);
    } catch (err) {
      console.log(err);
    }
  };


  return (      
        <Table  >
          <TableHead>
            <TableRow>
              <TableCell />
              <TableCell >
                Facility Code
              </TableCell>
              <TableCell >
                Facility Name
              
            </TableRow>
          </TableHead>
          <TableBody>
            {facility.map((item, idx) => {
              return (
                <>
                  <TableRow
                    key={idx}
                  >
                   
                    <TableCell >
                      {item.facility_code}
                    </TableCell>
                    <TableCell>{item.facility_name}</TableCell>
                   
                  </TableRow>
                 
                </>
              );
            })}
          </TableBody>
        </Table>
    
   
  );
}

export default Facility;

Data returned from API below

{
    "data": [
        {
            "facility_code": 148312,
            "facility_name": "Phc Marit",
        },
        {
            "facility_code": 767529,
            "facility_name": "FPL",       
        },   
    ]
}

I'm trying to map over data from API using material-ui table but I get facility.map is not a function. Please help me with a solution to this implementation.

Upvotes: 1

Views: 21232

Answers (4)

Asadbek A&#39;lamov
Asadbek A&#39;lamov

Reputation: 1

{facility.map((item, idx) => {
                  <TableRow
                    key={idx}
                  >
                   
                    <TableCell >
                      {item.facility_code}
                    </TableCell>
                    <TableCell>{item.facility_name}</TableCell>
                   
                  </TableRow>
})}

Upvotes: 0

joseglego
joseglego

Reputation: 2109

I created this example on codesanbox: https://codesandbox.io/s/hardcore-joana-xfybt?file=/src/App.js

There are multiple things that can go wrong.

First of all, you have to validate to have data before using the map. So you can do something like:

Step 1:

So, first change:

{facility.map((item, idx) => {

to this:

{facility && facility.map && facility.map((item, idx) => {

Step 2:

Also, take into consideration how you're receiving the answer, usually with axios. Because axios returns response. If you. want to access the body of the response is response.data, if your body also has data. Probably you need to do something like: fetch.data.data

(Check the getData function)

Upvotes: 8

Leinil
Leinil

Reputation: 133

Maybe you're trying to map a list that isn't there yet? Try doing this

{facility && facility.map((item, idx) => {

Upvotes: 0

Abiram
Abiram

Reputation: 401

When using Axios you have to use

fetch.data.data

I Also suggest you to use React useEffect with you do API Calls. The Recommended way of doing this is below.

import React from 'react';
import axios from 'axios';
import './App.css';

function App() {
  let [facility, setFacility] = React.useState([]);

  const fetchData = React.useCallback(() => {
    axios({
      "method": "GET",
      "url": "YOUR_API_ENDPOINT_HERE",
      "headers": {}, "params": {}
    })
      .then((response) => {

        const APIResponse = response.data // This is response data from AXIOS

        console.log("response: ", APIResponse.data) // This is response data from API

        setFacility(APIResponse.data) // Only Response from API is set in state

      })
      .catch((error) => {
        console.log(error)
      })
  }, [])

  React.useEffect(() => {
    fetchData()
  }, [fetchData])

  return (
    <div className="App">
      <Table  >
        <TableHead>
          <TableRow>
            <TableCell />
            <TableCell >
              Facility Code
            </TableCell>
            <TableCell >
              Facility Name
            </TableCell>
          </TableRow>
        </TableHead>
        <TableBody>
          {
            facility.map((item, idx) => {
              return (
                <>
                  <TableRow
                    key={idx}
                  >
                    <TableCell >
                      {item.facility_code}
                    </TableCell>
                    <TableCell>
                      {item.facility_name}
                    </TableCell>
                  </TableRow>
                </>
              );
            })
          }
        </TableBody>
      </Table>
    </div>
  );
}

export default App;

Upvotes: 1

Related Questions