I want to set the local state of a component using props obtained from mapStateToProps. When I use this.setState in ComponentWillMount() method or ComponentDidMount() method, it is undefined.
componentWillMount() {
this.props.fetchBooks(this.props.id);
this.setState({
books:this.props.books
})
}
const mapStateToProps = (state, ownProps) => {
let id = ownProps.match.params.book_id;
return {
id: id,
books: state.library.books,
};
};
The 'books' data is retrieved using the fetchBooks() function obtained by mapDispatchToProps. How can I set the sate using the props obtained from mapStateToProps?
componentWillMount
this method is deprecated and will be removed soon thus breaking your application if you update your React version. If you must have this in a lifecycle hook, I suggest verifying the props inshouldComponentUpdate
orcomponentDidUpdate
methods. – Baruchthis.props.fetchBooks(this.props.id);
do? Is it a thunk action fetching books? When you fetch the books the component continues rendering but the books are not there yet, maybe in the thunk action dispatch loading, ok or error actions so you can get these values from redux state. – HMR