Home > Net >  How to get object data and push an array in React?
How to get object data and push an array in React?

Time:09-22

I have an endpoint that returns an object. The object is:

{
"id": "669f8",
"creation_date": "2022-01-13 10:33:06.046652 01:00",
"case_type": "Summary",
"process_types": "",
"case_id": "ad23423s",
"current_stage": "",
"current_stage_name": "",
"consolidation": "None",
"last_change_date": "2022-01-14 14:35:17.563449 01:00",
"status": 1,
"assign": "Yes"

} I want to display it in my React project. Firstly I want to take object fields, and then the values.

I wrote this code:

class DetailsPage extends React.Component<DetailProps> {
  async getData() {
    const data = await Dependencies.backend.getList(this.props.url);
    if (data) {
      return data;
    }
    return [];
  }
  render() {
    const data = this.getData()
    const fields: string[][] = []
    const test: any[] = []
    data.then((val: any) =>
      fields.push(Object.keys(val))
      // console.log(val)
    )  .catch(err => console.log("There was an error:"   err))
    console.log("testeststt")
    console.log(fields)

    return (
      <div>
        <h1>Hoi!</h1>
      </div>
    );
  }
}

The console.log(fields) returns []

And when I open the array it shows

output

But I can't get the 0th row.

How can I get and push another array or something?

CodePudding user response:

The reason for this is that the render function only renders out the UI. It is not supposed to make asynchronous stuff. Since, you need to invoke the API call when the component mounts, you can do it in componentDidMount and when you have data, update it in state.

This way, on the initial render, you will have 0 items in the data. When you update the state, it will re-render the component and then you will have items in your data.

You can do something like the following:

componentDidMount() {
  this.getData()
}

async getData() {
  const data = await Dependencies.backend.getList(this.props.url);
  this.setState({ data: data ?? [] })
}

render() {
  const { data } = this.state;
  console.log(data)
}
  • Related