0

I'm working on a react.js project and I need to access an array of objects. I get the objects from an external URL and there's no issue there. Inside my component's render method I can see the array:

  const array = this.state.data.myArray;
  console.log({array});

Now I try to look at the first object:

  console.log({array}[0]);

but it's undefined.

I tried various combinations with or without the curly brackets but it's always undefined, or gives an unexpected token error.

How do I get to the array's objects?

EDIT:

Looks like my render method is called twice. The first time it's with the array undefined and the second time it has data, but by now it's no longer rendering.

Here's my component:

import React from 'react'
class Hello extends React.Component {

    constructor() {
        super();
        this.state = { data: [] };
    }


   async componentDidMount() {
      const url = 'http://localhost:9000/SomeJson/id';
      const response = await fetch(url);
      const data = await response.json();
      this.setState({ data });
      console.log(data); // data shows up in the console
   }

  render() {
      alert(this.state.data.theArray);

  return(
      <div><h2>hello</h2></div>
   );

  }
}
export default Hello;

What am I missing here?

3
  • 1
    it should be array[0] if array is a valid Array. can you show output for console.log(array); Commented Jan 28, 2020 at 15:35
  • No idea why you're putting curly brackets there, all it does is initialize an object with key array with value of your array. console.log(array[0]) is probably fine, if it isn't, you should show the output for console.log(array); as stated above Commented Jan 28, 2020 at 15:38
  • Thanks. Looks like my render method is called twice. I edited the question with more information. Commented Jan 28, 2020 at 18:33

1 Answer 1

1

const { myArray = [] } = this.state.data || {} You should check for data key to be a valid object and then destructure myArray out of it and then if myArray is undefined then initialise it with empty array.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks @Muhamman Ali. Looks like my render method is called twice. I edited the question with more information.
instantiate your data state with empty object instead of empty array.

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.