Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactJs - How to get updated state while inside a thunk promise

I am working on an application where prior to sending the data to the server we check if the fields are empty and fill them with dummy data.

State before sending data to server:

state = {
  title: '',
  body: ''
}

my dispatch function:

this.props.dispatch((dispatch) => {
  dispatch(initializeProcessForm());
  dispatch(processForm(state));
});

Inside initializeProcessForm I check if the fields are blank and fill them appropriately, but considering we should not mutate the state, I have to make a new state object and return.

Here, I loose the reference to the current (new state after function completes) and when dispatch(processForm(state)) submits to the server, it still holds the old data with blank fields.

How can I get around this problem without mutating the state react way?

The only way I can access the new state is once I am in inside the reducer but the API call happens inside the Action before going to the reducer when I am handling success or rejection of the form.

like image 745
Osama Shabrez Avatar asked Feb 04 '23 15:02

Osama Shabrez


1 Answers

The second argument passed to your thunks by redux-thunk is getState

this.props.dispatch((dispatch, getState) => {
  dispatch(initializeProcessForm());
  const updatedState = getState();
  dispatch(processForm(updatedState));
});
like image 154
Andy Ray Avatar answered Feb 07 '23 06:02

Andy Ray