Search code examples
reactjses6-promise

data.json is not a function error


How do I get data from my Promise.all?

I currenty get the error:

Possible Unhandled Promise Rejection (id: 0): TypeError: data.json is not a function TypeError: data.json is not a function

export function fetchEvents() {
    let pagesRequired = 0;
    return dispatch => {
        dispatch(isLoading(true));
        fetch(
            "http://wordpress.rguc.co.uk/index.php/wp-json/tribe/events/v1/events?per_page=50&categories=107"
        )
            .then(response => {
                return response;
            })
            .then(response => response.json())
            .then(data => {
                const apiPromises = [];
                pagesRequired = data.total_pages;

                for (let i = pagesRequired; i > 0; i--) {
                    apiPromises.push(
                        fetch(
                            "http://wordpress.rguc.co.uk/index.php/wp-json/tribe/events/v1/events?per_page=50&categories=107&page=" +
                                i
                        )
                    );
                }
                Promise.all(apiPromises)
                    .then(response => {
                        return response;
                    })
                    .then(data => {
                        console.log(data.json());
                    });
            });
    };
}

Solution

  • It should be:

    for (let i = pagesRequired; i > 0; i--) {
      apiPromises.push(
        fetch(
          "http://wordpress.rguc.co.uk/index.php/wp-json/tribe/events/v1/events?per_page=50&categories=107&page=" +
          i
        ).then(resp => resp.json())
      );
    }
    Promise.all(apiPromises)
      .then(data => {
        console.log(data);
      });
    

    apiPromises should collect promises that resolves to the thing you ultimately need. Then do Promise.all(apiPromises) to get the actual data. Here is a small demo with fetch to show how Promise.all API is working with fetch.