I have a weird problem when I console log my component on load to check if there is a state. I Get an array back with data. But when I try to loop through it. I get map undefined? I don't understand why it's driving me crazy.
What am i doing wrong? I used the same thing on other components without any problems.
Thanks!
My code:
import React, { Component } from 'react';
import ReactHtmlParser from 'react-html-parser';
// API settings
import { WP_DATA_URL } from 'constants/import';
// Axios fetching
import axios from 'axios';
// components
import Youtube from 'components/Youtube/Youtube';
import Slider from 'react-slick';
import SpinnerLoader from 'components/SpinnerLoader/SpinnerLoader';
class College extends Component {
state = {
page_college: [],
loading: true,
};
getCoffee() {
return new Promise(resolve => {
setTimeout(() => resolve('☕'), 1000); // it takes half of a second to make coffee
});
}
async showData() {
try {
const wpCollege = axios(`${WP_DATA_URL}/pages?slug=college`);
await this.getCoffee();
await Promise.all([wpCollege]).then(response => {
this.setState({
page_college: response[0].data[0].acf,
loading: false,
});
console.log(this.state.page_college);
});
} catch (e) {
console.error(e); // 💩
}
}
componentDidMount() {
this.showData();
}
render() {
const { loading } = this.state;
const { title, description, page_college: college } = this.state;
return (
<div className="pages--container">
<div className="pages">
<div className="row center-xs pages--wrapper">
<div className="page">
<div className="page--content">
{loading ? (
<SpinnerLoader />
) : (
<React.Fragment>
<div className="col-xs-12 col-md-5">
<h2>HOI</h2>
</div>
<div className="col-xs-12 col-md-6">
{college.map(data => {
console.log(data);
})}
</div>
</React.Fragment>
)}
</div>
</div>
</div>
</div>
</div>
);
}
}
export default College;
response[0].data[0].acf? Is it an array?console.log(typeof college)? I think you missing parsing JSON.response[0].data[0].acfis coming back asundefined? Logging aftersetStateis not reliable sincesetStateis asynchronous and you may be logging the old state and not the updated state