Home > Mobile >  multiple API calls in one componentDidMount using Axios in react
multiple API calls in one componentDidMount using Axios in react

Time:09-24

Here is my React js code for a single API call for a date range picker. now I want to call multiple API in React with componentDidMount Method is it possible if yes how can do that

import React,{ Component} from "react";
import axios from 'axios'

class PostList extends Component{
    constructor(props) {
        super(props)
    
        this.state = {
            posts: []
        }
    }
componentDidMount(){
    axios.get('http://127.0.0.1:8000/betweendays')
    .then(response => {
        this.setState({
            posts:response.data
        })
        console.log(response.data)
    })
}
    render() {
        const {posts} = this.state
        return (
            <div>
                <h1>get call in React js</h1>
                    {
                        posts.map(post => <div key = {post.id}>{post.id} </div>)
                    }
            </div>
        )
    }
}

export default PostList```

CodePudding user response:

Using .then() method to create chain of the requests..

componentDidMount() {
    axios.get('http://127.0.0.1:8000/betweendays')
        .then(response => {
            this.setState({
                posts: response.data
            })
            return response.data; //  returning response
        })
        .then(res => {
             // do another request Note we have the result from the above 
            // getting response returned before 
            console.log(res);
        })
        // Tag on .then here 
        .catch(error => console.log(error))
}

CodePudding user response:

You can add more apis in componentDidMount as u want.

componentDidMount(){
        axios.get('http://127.0.0.1:8000/betweendays')
        .then(response => {
            this.setState({
                posts:response.data
            })
            console.log(response.data)
        })
    axios.get('link')
        .then(response => {
            this.setState({
                posts:response.data
            })
            console.log(response.data)
        })
    }
  • Related