After pulling data from website, How to render it with component?

- 1 answer

Ad

I am pulling data from one website( url:https://restcountries.eu/rest/v1/) & data is getting displayed in console. I am using "axios" lib to fetch the data. But I want to render it with component. How to do it?

This is my code.

import React from 'react';
import axios from 'axios';

var Country ;

var fetchData = axios.create({
    baseURL: 'https://restcountries.eu/rest/v1/',
});

fetchData.get('https://restcountries.eu/rest/v1/')
            .then(
                function (response){
                    console.log(response)
                    Country = response.data
                    console.log(Country)            
                });


console.log(Country);


export default  React.createClass({

shouldCompoentUpdate: function(Country,response){
    return true;
    },

render(){
        return(
                <div>
                    <h3>States test</h3>
                </div>                      
            )   
    }           
});
Ad

Answer

Ad

Well, you are doing it wrong. First of all please read about React Component lifecycle and Loading Initial Data example. You need to get your data in componentDidMount() hook and set state when data is received.

React.createClass({
  getInitialState: function() {
    return { country: '' }
  },

  componentDidMount: function() {
    var fetchData = axios.create({
      baseURL: 'https://restcountries.eu/rest/v1/',
    });

    fetchData.get('https://restcountries.eu/rest/v1/')
    .then(function (response) {
      this.setState({ country: response.data});          
    }.bind(this));
  },

  render: function() {
    return <div>{this.state.country}</div>
  }
});
Ad
source: stackoverflow.com
Ad