Reputation: 497
I had initialized datas state as null array. I am trying to fetch data from axios post method like
componentDidMount(){
var a=this;
axios.post("http://localhost/axios/index.php")
.then((res)=>{
a.setState({datas:res.data});
});
console.log(this.state);
}
I am receiving
{0: {…}, 1: {…}, 2: {…}, 3: {…}, 4: {…}, 5: {…}}
0: {id: "1", typee: "class", user_id: "1"}
1: {id: "2", typee: "class", user_id: "1"}
2: {id: "3", typee: "course", user_id: "1"}
3: {id: "4", typee: "class", user_id: "2"}
4: {id: "5", typee: "test_series", user_id: "3"}
5: {id: "6", typee: "test_series", user_id: "2"}
this data if i console.log(res.data) but if i console.log(this.state) then it's still giving me null array
Upvotes: 0
Views: 45
Reputation: 629
setState
is asynchronous, so when you are console logging it, state has not yet been updated. You can use the callback form of setState
to get the updated state:
setState(
{ datas:res.data },
() => console.log(this.state)
);
more info here: https://reactjs.org/docs/react-component.html#setstate
Upvotes: 3