David Johns
David Johns

Reputation: 1714

How to get the length of an array in a state in React?

I have a React app with an API call. I'm setting a state with an initial array and set it to a JSON array in API call. I need to get the array length for a calculation. I tried the following code but didn't work! Console only says "Undefined"

componentDidMount() {
    API.get('project')
      .then(({ data }) => {
        this.setState({ 
          columns: data.response,
          ordered: Object.keys(data.response)
        }, () =>
          console.log("old ", this.state.columns.length)
        )
      })
      .catch((err) => {
        console.log("AXIOS ERROR: ", err);
      })
  }

Upvotes: 2

Views: 2393

Answers (1)

Patrick Ferreira
Patrick Ferreira

Reputation: 2053

Well, you are destructuring the response object from XHR and get directly the data field and then, you call again a .response on it. This is equivalent to write responseFromXHR.data.response. Try something like the following :

These 2 syntaxes are equivalent

// old syntax
axios.get('/user/12345')
  .then(function (response) {
    console.log(response.data);
  })

VS

// destructuring syntax
axios.get('/user/12345')
  .then(function ({data}) {
    console.log(data);
  })

I don't know exactly what you API retreives, but something like this seems better :

componentDidMount() {
    API.get('project')
      .then(({ data }) => {
        // debugger; // uncomment to display debugger in chrome and check `data` value
        this.setState({ 
          columns: data,
          ordered: Object.keys(data)
        }, () =>
          console.log("old ", this.state.columns.length)
        )
      })
      .catch((err) => {
        console.log("AXIOS ERROR: ", err);
      })
  }

Upvotes: 2

Related Questions