vivek modi
vivek modi

Reputation: 497

How to loop through axios response

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

Upvotes: 4

Views: 1602

Answers (1)

Cat_Enthusiast
Cat_Enthusiast

Reputation: 15688

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)
          );
    });
}

Upvotes: 2

Related Questions