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.
this.state.memesto be an empty array (memes: []) and arrays don't have adataproperty (this.state.memes.data.memes.forEach(...)). Initialize the data to match what your code expects. Also ifconsole.log(this.state.memes)displays{memes: ...}then that meansthis.state.memesactually has a propertymemes, so you would need to accessthis.state.memes.memes..... You should take a step back, think about how you want the data to look like that your component operators on and then make sure that you set that data correctly.console.log(this.state.memes)and see what you are getting.res.dataon API get. Ifres.datahas only:memes: [.....], then you may use de-structuring and try replacing:const memes = res.datawithconst {memes} = res.data;. Also, please see if you are able to use?.-> Optional chaining. So, instead ofthis.state.memes...you may trythis.state?.memes?.data?......