I have application (quiz-game) where user can click on button "New Game" and new game will start. I want to reset all my redux store when user is clicked on it. I have root reducer that combines all app reducers. And i want to reset them to initial state after clicking the button. I saw Dan Abramov answer (https://stackoverflow.com/a/35641992/11580012) and did the same, but nothing happens. I mean initial state doesn't set up.
Here some code bellow:
Component class
class GameMenu extends Component {
constructor(props) {
super(props);
this.state = {
modalIsOpen: false,
modalMessage: '',
modalType: undefined // 0 for new game, 1 for end game
};
this.openModal = this.openModal.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.handleCancel = this.handleCancel.bind(this);
}
openModal (e) {
this.setState({ modalIsOpen: true });
}
handleSubmit () {
this.setState({ modalIsOpen: false });
if(this.state.modalType === 0) {
this.props.startNewGame();
this.props.history.push('/');
} else {
this.props.endGame();
}
}
handleCancel () {
this.setState({ modalIsOpen: false });
}
render() {
return (
<div className="menu">
<button onClick={this.openModal} id="newGameButton">New Game</button>
<button>Leader Board</button>
<button onClick={this.openModal} id="endGameButton">End Game</button>
<Modal
isOpen={this.state.modalIsOpen}
onCancel={this.handleCancel}
onSubmit={this.handleSubmit}
>
<p>{this.state.modalMessage}</p>
</Modal>
</div>
)
}
}
const mapStateToProps = state => {
return {
players: state.players,
answeredQuestionsArray: state.questions.answeredQuestionsArray,
topics: state.questions.topics,
}
};
const mapDispatchToProps = {
startNewGame,
endGame
};
export default connect(
mapStateToProps,
mapDispatchToProps
)(GameMenu);
Root reducer:
import { questionsReducer } from "./questions/reducers";
import { playersReducer } from "./players/reducers";
import {START_NEW_GAME} from "./actions";
import {END_GAME} from "./actions";
const appReducer = combineReducers({
questions: questionsReducer,
players: playersReducer
});
const rootReducer = (state, action) => {
if (action.type === START_NEW_GAME) {
state = undefined;
}
return appReducer(state, action);
};
export default rootReducer;
const initialState = {
answeredQuestionsArray: [],
topics: []
};
export const questionsReducer = (state = initialState, action) => {
switch (action.type) {
case CHANGE_ANSWERED_QUESTIONS_ARRAY:
return {
...state,
answeredQuestionsArray: action.payload
};
case LOAD_TOPICS:
return {
...state,
topics: action.payload
};
}
return state;
};
export const startNewGame = () => ({
type: START_NEW_GAME
});
After this.props.history.push('/)
state doesn't change to initial.