Home > Blockchain >  How to fetch data from Instagram api with Axios and Reactjs?
How to fetch data from Instagram api with Axios and Reactjs?

Time:02-04

I want to make an api call with Instagram api using Axios/Reactjs i get already data but i am having rendering issue.I don't know where i make mistake but i cant render the caption or image from instagram post.thanks for help.

import React,{Component} from 'react'
import '../styles/home.css'
import '../App.css';
import axios from 'axios';


const api = axios.create({
    baseURL:`https://graph.instagram.com/me/media?fields=id,caption,media_url&access_token=IGQ.....` 
})

    class Home extends Component {

        state={
            courses: []
        }
        constructor(){
            super();
            api.get('/').then(res=>{
                console.log(res.data)
                this.setState({courses: res.data})
            })
    
        }
        createCourse = async()=> {
            let res = await api.post('/', {title:"Test", id:4 ,autor:'Test'})
            console.log(res);
        }
   

        render() {
          return
          <div>
              {this.state.courses.map(course => <h2 key={course.id}>{course.caption}</h2> )}
            <h1>Hello</h1>
           </div>
        }
      }
      export default Home;
  
  


// 

CodePudding user response:

You should fetch data in componentDidMount method.

componentDidMount() {
  api.get('/').then(res => {
    console.log(res.data)
    this.setState({courses: res.data})
  })
}

CodePudding user response:

You're trying to display the data before the fetch was completed.

Change your <div> from this:

<div>
    {this.state.courses.map(course => <h2 key={course.id}>{course.caption} 
    </h2>)}
    <h1>Hello</h1>
</div>

To this:

<div>
    {this.state.courses && this.state.courses.map(course => <h2 key={course.id}>{course.caption} 
    </h2>)}
    <h1>Hello</h1>
</div>

So it only renders when data isn't null.

-This is happening due to fetching before mounting, so in order to fix that, implement the componentDidMount() method.

  •  Tags:  
  • Related