4

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

1 Answer 1

2

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)
          );
    });
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.