简体   繁体   中英

Creating dynamic table with data fetched from API in JS React Bootstrap

I'm totally green in JS and I have a little problem. I want to create dynamic table with informations about cars. I fetch data from my friends API (i will show full json at the bottom of the post) and i can display it in log console. But I have no idea how to insert it into the table. This is my code:

const CarsClient = () => {

const [car, setCars] = useState({});

const getCarsList = async () => {
    const response = await fetch('http://localhost:3000/api/catalog/car?fbclid=IwAR0lOlJP-1kBKvQzn8GQ_3oYqVN5kTbRrlctDO6T10CJcumcPWfa7WVugQw');
    const jsonData = await response.json();
    setCars(jsonData);
    console.log(jsonData);
  };
useEffect(() => {
    getCarsList();
}, []);

    (...)
}
const renderCars = (car, index) => {
    return(
        <tr key={index}>
            <td>{car.id}</td>
            <td>{car.cost}</td>
    )
}
return (
    <>
<Container className="cont">
  (...)
      <ReactBootStrap.Table striped bordered hover>
            <thead>
                <tr>
                <th>#</th>
                <th>ID</th>
                <th>Price</th>
                </tr>
            </thead>
            <tbody>
                {
                    car.map(renderCars)
                }
            </tbody>
        </ReactBootStrap.Table>
        </Col>
    </Row>    
</Container>             
  </>
)

} export default CarsClient

And this is JSON: {"car":[{"id":1,"cost":250,"VIN":2334433,"availability":true,"CarModelId":1,"CarModel":{"id":1,"name":"X5","fuel":"ON","body":"SUV","productionYear":2020,"enginePower":200,"MakeId":1,"Make":{"id":1,"name":"BMW"}}},{"id":2,"cost":275,"VIN":2334433,"availability":true,"CarModelId":2,"CarModel":{"id":2,"name":"Q7","fuel":"ON","body":"SUV","productionYear":2019,"enginePower":220,"MakeId":2,"Make":{"id":2,"name":"AUDI"}}}]}

I have this error: CarsClient.js:96 Uncaught TypeError: car.map is not a function

it is better to declere the car object as:

const [car, setCars] = useState([]);

and loop over the array:

by the way I reproduced it without api call and the problem is on the car.car.map. have a look at the below link:
https://codesandbox.io/s/patient-wildflower-pjfbk?file=/src/Car.js:848-865

You car here is an object and not an array sou should do the following
in you getCarList :

setCars(jsonData.car)

and on your state definition:

const [car, setCars] = useState([]);

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