4

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.

1 Answer 1

8

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));
});

Not the answer you're looking for? Browse other questions tagged or ask your own question.