Skip to content
Advertisement

Redux loses state when navigating to another page

I am building a web application using React and Redux. Redux works when I set the state on that page and then reaccess it through a statement like this.props.book.bookTitle, however, when I navigate to another page, redux loses it’s state and defaults to the initialState. Here is my code:

bookDuck.js:

JavaScript

reducer.js:

JavaScript

store.js:

JavaScript

index.js:

JavaScript

In the following piece of code, I set the state, and navigate to a new window.

JavaScript

This is performed in a childComponent. I made a test button in it’s parent component that access this.props.book from the store without navigating to a new page, and it accesses the properties in redux just fine. But as soon as I navigate to a new page using window.location, the redux value returns to it’s initial state of:

JavaScript

I am also connecting to the store when exporting the class like this:

export default connect(state => ({book: state.book}))(AddMembers);

Does anyone know what I could be doing wrong? I appreciate the help.

Advertisement

Answer

Redux state doesn’t remain after a page reload. window.location = '/addMembers' cause a page reload and it’s not the correct way to programmatically navigate to another page when you use react-router. Instead of that you should use this.props.history.push('/addMembers').

Read answers to this question to get an idea about how to programmatically navigate in react-router.

Advertisement