import React from "react"; import { connect } from "react-redux"; import * as courseActions from "../../redux/actions/courseActions"; import * as authorActions from "../../redux/actions/authorActions"; import PropTypes from "prop-types"; import { bindActionCreators } from "redux"; import CourseList from "./CourseList"; import { Redirect } from "react-router-dom"; class CoursesPage extends React.Component { state = { redirectToAddCoursePage: false }; componentDidMount() { const { courses, authors, actions } = this.props; if (courses.length === 0) { actions.loadCourses().catch((error) => { alert("Loading courses failed. " + error); }); } if (authors.length === 0) { actions.loadAuthors().catch((error) => { alert("Loading authors failed. " + error); }); } } render() { return ( <> {this.state.redirectToAddCoursePage && }

Courses

); } } CoursesPage.propTypes = { courses: PropTypes.array.isRequired, authors: PropTypes.array.isRequired, actions: PropTypes.object.isRequired }; function mapStateToProps(state) { return { courses: state.authors.length === 0 ? [] : state.courses.map((course) => { const author = state.authors.find((a) => a.id === course.authorId); return { ...course, authorName: author.name }; }), authors: state.authors }; } function mapDispatchToProps(dispatch) { return { actions: bindActionCreators( { loadCourses: courseActions.loadCourses, loadAuthors: authorActions.loadAuthors }, dispatch ) }; } export default connect(mapStateToProps, mapDispatchToProps)(CoursesPage);