I am new to React and finding it difficult to accomplish Thunk. I have read few questions and also guide but am unable to understand it properly.
I know that I have to connect but I am all lost. Please help.
Single dispatch works fine, but the double dispatch does not work at all. No log is printed.
handleSubmit(event)
{
event.preventDefault();
this.isLoading = true;
// TWO EVENTS needed, first to add new player and then set as bowler
if (this.state.showAddBowlerTextfield) {
utilPostJSON(jsonURL + 'add-player.php', {
name: this.state.bowlerName,
matchId: this.currState.matchId,
inningsId: this.currState.inningsId,
teamId: this.currState.teamBowling.id,
isBowler: true
})
.then((response) => {
console.log('Success', response);
this.setState({
bowlerId: response.data.id,
bowlerName: response.data.name,
});
this.dispatchAddPlayerAndAddBowler();
})
.catch((error) => {
console.error('Error', error);
});
return
}
// This needs only one dispatch
const {store} = this.context;
this.currState = store.getState();
store.dispatch({
type: constants.NEW_BOWLER,
payload: this.state
});
this.props.parentClose();
}
//This function sends two dispatches
dispatchAddPlayerAndAddBowler()
{
console.log('dispatchAddPlayerAndAddBowler');
return (dispatch, getState) => {
const {store} = this.context;
console.log('Store', store);
store.dispatch({
type: constants.NEW_PLAYER_BOWLER,
payload: this.state
});
store.dispatch({
type: constants.NEW_BOWLER,
payload: this.state
});
}
}
The output of the log is:
Success {data: {…}, status: 200, statusText: "OK", headers: {…}, config: {…}, …}
dispatchAddPlayerAndAddBowler
You are using thunks wrong. Try refactoring dispatchAddPlayerAndAddBowler
:
dispatchAddPlayerAndAddBowler() {
console.log('dispatchAddPlayerAndAddBowler');
return (dispatch, getState) => {
// Wrong: const {store} = this.context;
// you don't need to do this dispatch is already there in the first parameter
dispatch({
type: constants.NEW_PLAYER_BOWLER,
payload: this.state
});
dispatch({
type: constants.NEW_BOWLER,
payload: this.state
});
}
}
Also you should use connect
and mapDispatchToProps
for handleSubmit