添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接

How to wait for a PUT saga to finish (saga composition)? #886

Closed
@frankandrobot

Description

Here's the use case: the createTag (see below) creates something in the database and then syncs the database with redux. So far nothing out of the ordinary. However, notice that if you call createTag directly multiple times, this will corrupt the redux state when ajax requests come out of order (or error out)---hence, all createTag requests are made by dispatching a CREATE_TAG (and letting takeLatest coordinate multiple requests).

That means that if another saga needs to run createTag , it must do a yield put(CREATE_TAG) .

The question then is really about composing sagas. Say, for example, I need a createTagAndDoSomething . This saga needs to dispatch CREATE_TAG and then wait for it to finish before "doing something".

What's the best way to do this? Create an extra variable in redux state? dispatch another action? (Neither of these feel right.)

Alternatively, does redux-saga have a way of knowing when the action completes?

 function *createTag(action)




    
 {
   const {name} = action.payload;
    // create tag
    yield call(Api.create, {name}); 
    // then fetch all
    const tags = yield call(Api.listTags);
    // store in redux state
    yield put(setTagData({tags}));
   // everything is wrapped in a try/catch but not shown here
function *createTagAndDoSomething() {
  // how to wait for this to finish?
  yield put(CREATE_TAG)
  // do something when createTag finishes 
/// setup listeners
takeLatest(CREATE_TAG, createSaga)
takeLatest(CREATE_TAG_AND_DO_SOMETHING, createTagAndDoSomething)

UPDATED: added concrete example as per a co-worker's feedback