Setting State From Axios Response And Using It In Render
I have this current situation in react where the state is not getting set and if set cannot be used in render.
componentDidMount() {
axios.get(`url`)
.then(function(response){
const test = response.data;
this.setState({
data:test
});
}.bind(this));
setTimeout(function test(){
console.log('filterdata',this.state.data);
},2000);
}
This is my sample code that I have been trying to use but the problem here is even though I am setting the state the global this does not contain the value. I have done bind to prevent the same. I have tried two other things as well
componentDidMount() {
axios.get(`url`)
.then((response)=>{
this.setState({
data:response.data
});
});
setTimeout(function test(){
console.log('filterdata',this.state.data.templateFields);
},6000);
}
as well as this
componentDidMount() {
var self = this;
axios.get(`url`)
.then(function demo(response){
self.setState({
data:response.data
});
});
setTimeout(function test(){
console.log('filterdata',self.state.data.templateFields);
},6000);
}
The last one has the value in self but cannot be used in render where I am using "this" like this
<ul className="filter-options">
{
this.state.data.map(function(val){
<p>{val.templateFields}</p>
}, this)
Is it really that difficult in react to get a simple promise and use it?Is there a better way to do it that I might not know about?
Answer
First thing, always use arrow functions instead of classic function
declaration so you have this
context passed along automatically.
Regarding your console.log
do not try to log the state after you set it in componentDidMount
the setState, and you request, are asynchronous.
You should always log the state in the render, or sometimes maybe in the componentDidUpdate
eventually.
Take a look at this, this should work:
componentDidMount() {
axios.get(`http://nextgen-bcs-dev-1008264651.ap-south-1.elb.amazonaws.com/templateConfig/site6/VAULT`)
.then((response) => {
this.setState({
data: response.data
});
}).catch((error) => {
console.error(error);
});
}
render () {
console.log(this.state.data)
return (
<ul className="filter-options">
{
this.state.data.map((val) => {
<p>{val.templateFields}</p>
})
}
</ul>
);
}
If it doesn't, then your issue is somewhere else.
Related Questions
- → 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?