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)?
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.
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.
Using the saga, we can dispatch actions with the put effect. Another example of making async calls using saga is shown below.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With