1

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!

  • 1
    `fetch` is asynchronous. At the moment `return ...` is executed and `res_list` is evaluated, the assignment to `res_list` hasn't happened yet. See [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/q/23667086/218196) . 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. – Felix Kling Dec 03 '20 at 13:55
  • 1
    i do not use react but dont you need to use something like `let [res_list, setList] = useState([])` and then setting it like ... `setList(res_list)` in the `.then()` block? – bill.gates Dec 03 '20 at 13:59
  • 1
    Thanks a lot @FelixKling! I also noticed that there were approx. millions of network requests with the `fetch` in the `render` method - put it in the `componentDidMount()`! – marcusmerkel Dec 03 '20 at 14:33

1 Answers1

1

res_list isn't available to you where you want to return it. In the then() block, put the returned array into state and use this state then in the return block.

userjmillohara
  • 457
  • 5
  • 25