Home > front end >  Undefined Element Returned From Array in React
Undefined Element Returned From Array in React

Time:09-26

I have a class component which makes an async call before render() and stores the result into its state. The async call is called before render with componentWillMount() which uses this.renderData(). The async response returns an array of arrays but in this case I am only interested in the first array. So I store the result collections.first into the state arrayData. I can successfully console.log the state arrayData which shows 8 elements (see screenshow). However, when I try to access an element with an index using Array.at(index) or Array[index] I get an undefined error.

How do I properly retrieve the index? The overall goal is to retrieve a value from the result and display an image in the render function <img src={this.state.arrayData.at[2].url}> </img>/ But Im unsure why Undefined is happening.

Here is what I have so far:

class Gallery extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      arrayData: null,
    };
  }

  renderData = async () => {
      // async request code here which sets fetchURL and requestOptions
      const collections = await fetch(fetchURL, requestOptions).then((data) =>
        data.json()
      );
      if (collections ) {
        this.setState({ arrayData: collections.first });
      }
    }
  };

  componentWillMount() {
    this.renderData ();
  }

  render() {
     
     console.log(this.state.arrayData); // correctly outputs array of length 8 (see output below)
     console.log(this.state.arrayData[2]); // undefined error 
     console.log(this.state.arrayData.at(2); // undefined error

     return(
         // some render code 
         <img src={this.state.arrayData.at[2].url}> </img> // cant retrieve
    );
  }
}

Array output from response shows 8 items fine when logging as this.state.arrayData enter image description here

Error Code when logging with console.log(this.state.arrayData[2]);

react-refresh-runtime.development.js:315 Uncaught TypeError: Cannot read properties of null (reading '2')
    at Gallery.render (Gallery.jsx:61:1)
    at finishClassComponent (react-dom.development.js:19752:1)
    at updateClassComponent (react-dom.development.js:19698:1)
    at beginWork (react-dom.development.js:21611:1)
    at beginWork$1 (react-dom.development.js:27426:1)
    at performUnitOfWork (react-dom.development.js:26557:1)
    at workLoopSync (react-dom.development.js:26466:1)
    at renderRootSync (react-dom.development.js:26434:1)
    at recoverFromConcurrentError (react-dom.development.js:25850:1)
    at performSyncWorkOnRoot (react-dom.development.js:26096:1)

Error Code when logging with console.log(this.state.arrayData.at(2));

Uncaught TypeError: Cannot read properties of null (reading 'at')
    at Gallery.render (Gallery.jsx:61:1)
    at finishClassComponent (react-dom.development.js:19752:1)
    at updateClassComponent (react-dom.development.js:19698:1)
    at beginWork (react-dom.development.js:21611:1)
    at beginWork$1 (react-dom.development.js:27426:1)
    at performUnitOfWork (react-dom.development.js:26557:1)
    at workLoopSync (react-dom.development.js:26466:1)
    at renderRootSync (react-dom.development.js:26434:1)
    at recoverFromConcurrentError (react-dom.development.js:25850:1)
    at performSyncWorkOnRoot (react-dom.development.js:26096:1)

CodePudding user response:

I will explain what is happening here :

In the first time when you render the component the this.state.arrayData it's undefined , and after the data it's fetched from the server the component render again and you can see the result of the responce in your console , but when you try to access the the array at index 2 and the data is undefined you will get this error .

So the solution it's easy check if the this.state.arrayData it's true then display the component else make a loading component .

  render() {
    if (!this.state.arrayData) {
        return <h1>...Loading</h1>
    } 
     return(
         // some render code 
         <img src={this.state.arrayData.at[2].url}> </img> // cant 
      retrieve
    );
  }
  • Related