After pulling data from website, How to render it with component?
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
Related Questions
Ad
- → Import statement and Babel
- → should I choose reactjs+f7 or f7+vue.js?
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → .tsx webpack compile fails: Unexpected token <
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → React Native with visual studio 2015 IDE
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
- → How do I determine if a new ReactJS session and/or Browser session has started?
- → Alt @decorators in React-Native
- → How to dynamically add class to parent div of focused input field?
Ad