Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling redux-form dispatch(change) from within a redux-saga

I have a saga that posts to a webservice and returns a new sales order number to state. This is working great and looks like this.

//New SALES NUMBER SAGA
function getNewSalesNumber(salesRepId, typeId) {
  const url = `${baseUrl}/api/SalesOrder/${salesRepId}?typeId=${typeId}`;
  console.log(url);
  return axios.post(url);
}

function* callGetNewSalesNumber({salesRepId, typeId, resolve, reject}) {
  const result = yield call(getNewSalesNumber, salesRepId, typeId)
    if (result.data) {
    yield put({type: "NEWSALESNUMBER_FETCHED", result});
//    yield call(resolve); 
    } else {
//    yield call(reject);
  }
}

function* getNewSalesNumberSaga() {
  yield* takeEvery("FETCH_NEWSALESNUMBER", callGetNewSalesNumber);
}

The reducer looks like this.

    function newSalesNumber(state = {}, action) {
  switch(action.type) {
    case 'NEWSALESNUMBER_FETCHED':
      return state
        .set("orderHeader.orderId", action.result);
    default:
      return state;
  }
}

export default newSalesNumber;

I'm trying to figure out what my options are for returning that value to newSalesNumber (which is now in state) to a Field.

If I was doing this from within the form component I would use something like this...

 this.props.dispatch(change('mainForm', 'orderNumber', "testNumber"));

Is there a way to do this from within the saga after the data is received> Can I call dispatch(change) from outside of the connected form (in Saga)?

like image 522
Shawn Matthews Avatar asked Mar 16 '18 03:03

Shawn Matthews


People also ask

How do I dispatch another action from Saga?

Create a plain JavaScript Object to instruct the middleware that we need to dispatch some action, and let the middleware perform the real dispatch. This way we can test the Generator's dispatch in the same way: by inspecting the yielded Effect and making sure it contains the correct instructions.

What happens when you try to dispatch an action within a reducer?

Dispatching an action within a reducer is an anti-pattern. Your reducer should be without side effects, simply digesting the action payload and returning a new state object. Adding listeners and dispatching actions within the reducer can lead to chained actions and other side effects.

Which keyword do we use to dispatch an action in sagas?

Using the saga, we can dispatch actions with the put effect. Another example of making async calls using saga is shown below.


1 Answers

You can do it directly from sagas like this(we are using this in our project)

yield put(change('form_name', 'property_name', value_for_the_property))

Or you can return the data through reducers and use it in the container level to update your redux form.

like image 131
Mustafa Mamun Avatar answered Sep 28 '22 00:09

Mustafa Mamun