I have a JSON API response that I would like to map into a list of Child-Components, called <ReservationBox />, like this:
render() {
// ... other code ...
let res_list = [];
fetch(request)
.then(response => response.json())
.then(reservations => {
console.log(reservations)
res_list = reservations.map((res) => <ReservationBox key={res.id} court={res.court} date={res.day} start_time={res.start} end_time={res.end} />);
console.log(this.res_list);
});
return (
<div>
{heading}
{res_list}
</div>
);
}
Now, my reservations log correctly, and also the res_list appears correctly in the console as an array of React Components, but it won't render in the parent component.
Any idea or help will be highly appreciated, because I could not find anything on this. Thanks in advance!
fetchis asynchronous. At the momentreturn ...is executed andres_listis evaluated, the assignment tores_listhasn't happened yet. See Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference . If you think about it, it's conceptually wrong to make a network request every time the component renders. You should make the network request in response to some event, update the component's state, which in turn will cause the component to rerender.let [res_list, setList] = useState([])and then setting it like ...setList(res_list)in the.then()block?fetchin therendermethod - put it in thecomponentDidMount()!