Search code examples
javascriptreactjsfetch-api

Problem with nested fetch request in React


New to React, I'm currently trying to create a data table with data from an API. I want to have a first fetch, and then run another with response from the first (id) in order to complete my table.

Here is my code:

class HomePage extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            user: {},
            data: []
        };
    }

    componentDidMount() {
        this.setState({
            user: JSON.parse(localStorage.getItem('user'))
        }, function () {
            this.loadAllObjectsInfo()
        });
    }

    // Fetch all object info in order to fill the table
    loadAllObjectsInfo() {
        const requestOptions = {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
                'bbuser': this.state.user.userId,
                'bbtoken': this.state.user.secret
            },
        };

        fetch('https://xxxxx/api/objects', requestOptions)
            .then(response => response.json())
            .then((data) => {
                this.setState({ data: data })
            })

    }

With this code, I have the data I want to render my table but I need to run another fetch to get other info with the id coming from the first request.

How can I do that nested fetch request?


Solution

  • You can write the code as below.

    fetch('https://xxxxx/api/objects', requestOptions)
    .then(response => response.json())
    .then((res1) => {
    
        fetch('https://xxxxx/api/objects', requestOptions)
        .then(response => response.json())
        .then((res2) => {
            this.setState({ data: res2 });
        });
    
    });
    

    Hope this will work for you!