rxc-app/src/components/courses/CoursesPage.js

86 lines
2.1 KiB
JavaScript

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 && <Redirect to="/course" />}
<h2>Courses</h2>
<button
style={{ marginBottom: 20 }}
className="btn btn-primary add-course"
onClick={() => this.setState({ redirectToAddCoursePage: true })}
>
Add Course
</button>
<CourseList courses={this.props.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);