Home > Software design >  React Can't Access Array Inside Object
React Can't Access Array Inside Object

Time:03-30

I'm trying to access an array within an object. The object form is:

{memes : { 
    data: {memes: Array(100)}
    success: true 
}}

import React from 'react';
import API from './functions/api';
import styles from './App.module.css';

class App extends React.Component {

  state = {
    memes: []
  }

  componentDidMount(){
    API.get().then(
      res => {
        // axios function returns Object
        const memes = res.data

        this.setState({ memes })
      }
    )
  }

  displayMemes(){

    console.log( this.state.memes );
    
    // memes: {
    //   data: {
    //     memes: Array(100)
    //   }
    // }

    this.state.memes.data.memes.forEach( meme => { 
      // Cannot read properties of undefined (reading 'forEach')...
    });
  }

  render(){
    return(
      <div className={ styles.container }>
        { this.displayMemes() }
      </div>
    )
  }
}

export default App;

Clearly I don't know what I'm doing wrong, I'm fairly new to this, the solution has to be simple.

I'm trying to get data from an open API ('https://api.imgflip.com/get_memes') to practise implementing different types of React apps.

CodePudding user response:

Calling an API is an asynchronous action which takes some time to resolve.
You can initialize memes with a null value first.

state = {
  memes: null
}

Check if memes is not null before calling displayMemes so that you prevent calling it before getting the API response.

  render(){
    return(
      <div className={styles.container}>
        {this.state.memes && this.displayMemes()}
      </div>
    )
  }

CodePudding user response:

        const memes = res.data.memes

        this.setState({ memes })
  • Related