I need to load article from DB and set it like a component's state. Then this article should be shown on the page. But when I try to do this, there is an error that the value of loaded article's state is undefined. So, I think that the problem occures because the loading data function is called after the component's render. How can I call this function before rendering and properly show state's value?
import React from 'react';
import axios from 'axios';
import { connect } from 'react-redux';
import { withRouter } from "react-router";
class ArticlePage extends React.Component {
constructor(props) {
super(props);
this.state = {
article: null,
}
}
componentDidMount() {
const { onLoad } = this.props;
// gets full list of articles
axios('http://localhost:8080/api/articles')
.then((res) => onLoad(res.data))
}
getArticle() {
// gets current article
// ...
}
render() {
this.getArticle();
const { article } = this.state;
return (
<div>
<h1>
{article.title}
</h1>
</div>
);
}
}
const mapStateToProps = state => ({
articles: state.home.articles,
});
const mapDispatchToProps = dispatch => ({
onLoad: data => dispatch({ type: 'HOME_PAGE_LOADED', data }),
onDelete: id => dispatch({ type: 'DELETE_ARTICLE', id }),
setEdit: article => dispatch({ type: 'SET_EDIT', article }),
});
export default connect(mapStateToProps, mapDispatchToProps)(withRouter(ArticlePage));