I'm facing an issue in ReactJS. How should I get the value from appointments data eg start_date
and staff data full_name
rest api data
"appointments": [
{
"id": "10",
"staff_id": "1",
"start_date": "2020-05-12 10:30:00",
"end_date": "2020-05-12 11:00:00",
}
],
"staff": [
{
"id": "2",
"full_name": "Barbershop"
}
]
my component
this.state = {
appointmentdata:[],
}
componentDidMount() {
axios.get(`http://localhost/v1/appointments/`)
.then(res => {
console.log(res);
const appointmentdata = res.data;
console.log(appointmentdata);
this.setState({ appointmentdata});
})
}
//how i should get the value of staff array fullname
{this.state.appointmentdata.staff.map(({ full_name }, i) => (
<div className="full-block">
<p key={i}>
{full_name} //full_name it is not working
</p></div>
)
)}
what should i do? anyone help me?
You can create a map before actually using it. To create the map take the staff
array and an object map, assuming the id
of staff array corresponds to appointment id.
var staffMap = staff.reduce((res, item) => { res[item.id] = item; return res; }
Now you can use the staff map in the render function.
this.state.appointments.map(appointment => {
return <div> {appointment.start_data} {staffMap[appointment.id].full_name} </div>
});
Try adding this.state.appointmentdata
to check if appointmentdata is not undefined.
You can also use id
for key value, because (I guess) it's unique key in DB. Then you can remove i
from parametes.
{this.state.appointmentdata && this.state.appointmentdata.staff.map(({ id, full_name }) => (
<div className="full-block">
<p key={id}>
{full_name}
</p>
</div>
))}
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.