I have a api call and set the response in state like
componentDidMount(){
var a=this;
axios.post("http://localhost/axios/index.php")
.then((res)=>{
console.log(res.data);
a.setState(
{ datas:res.data },
() => console.log(this.state.datas)
);
});
}
I am getting
{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"}
in state. I want to show this data in table format so tried
render(){
return(
<table>
<thead>
<tr>
<th>S.No.</th>
<th>Type</th>
</tr>
</thead>
<tbody>
{
this.state.datas.map(data=>(
<tr key={data.id}>
<td>{data.id}</td>
<td>{data.typee}</td>
</tr>
))
}
</tbody>
</table>
)
}
but it's giving me this.state.datas.map is not a function
i had initialized my data state as null array
Thats because res.data is an object, not an array. I suppose you could transform it into an array of objects before you assign it to your state.
Just use the Object.values() method available in ES6 which will create an array using all values of key-value pairs in an object.
componentDidMount(){
var a=this;
axios.post("http://localhost/axios/index.php")
.then((res)=>{
a.setState(
{ datas: Object.values(res.data) },
() => console.log(this.state.datas)
);
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With