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!

3
  • 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 . 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. Commented Dec 3, 2020 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? Commented Dec 3, 2020 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()! Commented Dec 3, 2020 at 14:33

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.