0

I'm using Ant Design's Modal.confirm within my saga and I'm trying to pass a callback that dispatches an action in one of the modal params.

I've tried using channels explain in this post, but I think I've gotten the wrong idea on how to tackle this problem.

function* editCustomer(action) {
  try {
let postBody = { overwrite: action.payload.overwrite }
    let customerResponse = yield call(_api.execute, url, "POST", postBody);
  } catch (error) {
    if (statusCode === 409) {
     /// duplicate data, pass in overwrite
      Modal.confirm({
        title: 'Sample title',
        onOk: () => {
          editCustomerChannel.put(_customerActions.editCustomer({ 
            overwrite: true 
         }))
        }
      })      

    } else {
      yield put({ type: "CUSTOMERS__EDIT_CUSTOMER_FAILED" });
    }
  }
}

/// CustomerSagas
export default [
  takeEvery('CUSTOMERS__SET_CUSTOMER_OWNER', setCustomerOwner),
];
export default function* rootSaga() {
    yield all([...CustomersSagas]);
}

My sample code shows the editCustomer saga. I'm expecting _api.execute to throw an error within in the try/catch block, then Modal.confirm is called with the callback to call editCustomer again with the overwrite key set to true. My problem is I can't dispatch editCustomer in the callback.

How should I tackle this problem?

Thanks!

John Wong
  • 220
  • 2
  • 7

1 Answers1

0

I would try to use store.dispatch() directly:

# Wherever your configured store is
import { store } from './store' 

function* editCustomer(action) {
  try {
let postBody = { overwrite: action.payload.overwrite }
    let customerResponse = yield call(_api.execute, url, "POST", postBody);
  } catch (error) {
    if (statusCode === 409) {
     /// duplicate data, pass in overwrite
      yield call([Modal, 'confirm'], {
        title: 'Sample title',
        onOk: () => {
          store.dispatch(_customerActions.editCustomer({ 
            overwrite: true 
         }))
        })
      })      

    } else {
      yield put({ type: "CUSTOMERS__EDIT_CUSTOMER_FAILED" });
    }
  }
}

Notice that I also replaced Modal.confirm({...}) with yield call([Modal, 'confirm'], ...) which is not directly related to your problem but is generally the correct way to make function calls to external APIs/tools/etc within a saga.

Amr Mostafa
  • 23,147
  • 2
  • 29
  • 24