I have a form wherein I insert values into the store and redirect to another page to display all the values from redux store.
How do we access data from store in a redirected page?
I was looking for working example to see how store.subscribe. I was trying different example but was not successful.
would appreciate your help.
import React from "react";
import { connect } from "react-redux";
import * as courseActions from "../../redux/actions/courseActions";
import PropTypes from "prop-types";
import { bindActionCreators } from "redux";
import history from './history'
class CoursesPage extends React.Component {
state = {
course: {
title: "",
},
};
handleSubmit = (event) => {
event.preventDefault();
this.props.actions.loadCourses.createCourse(this.state.course).then(() => {
this.props.history.push('/allcourses');
};
render() {
return (
<div>
<form onSubmit={this.handleSubmit}>
<h2>Courses</h2>
<h3>Add Course</h3>
<input type="submit" value="Add Course" />
{this.props.courses.map((course) => (
<div key={course.title}>{course.title}</div>
))}
</form>
<hr />
</div>
);
}
}
CoursesPage.propTypes = {
courses: PropTypes.array.isRequired,
actions: PropTypes.object.isRequired,
};
function mapStateToProps(state) {
return {
courses: state.courses,
};
}
function mapDispatchToProps(dispatch) {
return {
actions: {
loadCourses: bindActionCreators(courseActions, dispatch),
},
};
}
export default connect(mapStateToProps, mapDispatchToProps)(CoursesPage);
AllCourses.js
import React from "react";
import store from "../../redux/configureStore"
class AllCourses extends React.Component {
constructor(props) {
super(props);
this.state = {
courses: [],
};
store.subscribe(() => {
this.setState({
courses: store.getState.courses
});
});
}
render() {
return (
<div>
{this.state.courses.map((course) => <div key={course.title}>{course.title}</div> )}
</div>
);
}
}
export default AllCourses;
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…