简体   繁体   中英

How to show data fetched from API inside React array map

I am trying to map an array of objects inside a React functional component. Here is a part of my object:

[{"id":1,"name":"Cordoba Park","start_date":"2020-03-19","address":null,"region":1,"country":2}] 

My problem is how to map this object into a table and fetch from the API the region and country by Id at the same time. I am using Redux hooks to fetch data from my API.

<tbody>
  {
    hotels.payload.map((hotel) => (
        <tr key={hotel.id}>
            <td>
                <div className="d-flex flex-column">
                    <h5>{hotel.name}</h5>
                    <p className="text-muted">{hotel.chain}</p>
                </div>
            </td>
            <td>{hotel.country}</td>
            <td>{hotel.region}</td>
            <td>
                <Badge className="p-2" variant={hotel.active ? 'success' : 'danger'}>
                    {hotel.active ? 'Activo' : 'Inactivo'}
                </Badge>
            </td>
            <td>
                <Button className="mx-1" variant="light">
                    <i className="fas fa-edit" />
                </Button>
                <Button className="mx-1" variant="light">
                    <i className="fas fa-trash" />
                </Button>
            </td>
        </tr>
    ));
 }
</tbody>

It's not a good idea to make an API call inside the render function. It's called each time any prop is updated and therefore you'll have too many api calls and a very bad performance.

You should reorganize your code to load the data first and then render the results

Ideally, I would try to get the data from the source in the first API call but I assume that it's not possible...

If not, in the redux action you should query for the hotel results one by one and update the store only once.

You can have a look at the axios library to make your call

There is a nice Axios.all() utility that lets you make all the API calls and wait for all results before calling the callback function. Axios All example

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM