Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to loop through axios response

Tags:

reactjs

axios

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

like image 650
vivek modi Avatar asked Sep 15 '25 10:09

vivek modi


1 Answers

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)
          );
    });
}
like image 112
Chris Ngo Avatar answered Sep 18 '25 04:09

Chris Ngo