Reputation: 95
Hello i'm building React web application that has CRUD for "Fleet car manager". I'm using axios libraries to get/post requests to and from my api controller written in Spring Boot. I've builded Table where i want to render data i got from 2 axios get methods /car
Data from /car and /company
Data from /company.
This is how i render data from /car
{this.state.cars.map(car =>
<tr key={car.idCar}>
<td>{car.carBrand}</td>
<td>{car.carModel}</td>
<td>{car.carManufactureYear}</td>
<td>{car.carType}</td>
<td>{car.engineCapacity}</td>
<td>{car.enginePower}</td>
<td>{car.plateNumber}</td>
<td>{car.id_company}</td>
<td styles="text-align: center, display: inline-block">
Works just fine Result
Now i want to replace this car.id_company
with name of company which i got from axios.get(localhost:8080/company)
Any tips how to do this?
Upvotes: 1
Views: 716
Reputation: 531
Yes you can achieve it by creating a function, you need to pass a value and return filtered first data to get the name.
import React, { useState } from 'react';
const MyComponent = () => {
const [company, setCompany] = useState([
{
idCompany: 1,
name: "xyz",
},
{
idCompany: 2,
name: "Abc",
}
]);
const [car, setCar] = useState([
{
idCar: 1,
id_company: 2,
name: "A"
},
{
idCar: 2,
id_company: 1,
name: "B"
}
])
// filter company name and get data from frist data
const companyName = (id) => {
let tempCompany = company.filter((c) => {
return c.idCompany === id
})
console.log(tempCompany[0]);
return tempCompany[0].name;
}
return (
<table>
<tr>
<th>Car name</th>
<th>Company</th>
</tr>
{car.map((item, index) => {
return (
<tr key={index}>
<td>{item.name}</td>
<td>{companyName(item.id_company)}</td>
</tr>
)
})}
</table>
)
}
export default MyComponent
Upvotes: 1
Reputation: 1789
After you have get the info from /company
, just make an object by using reduce
to store the mapping info.
const mapping = res.reduce((idNameMapping, elem) => {
idNameMapping[id] = elem.name
return idNameMapping
} , {})
{this.state.cars.map(car =>
//more on top
<td>{mapping[car.id_company]}</td>
// more down below
Upvotes: 2