最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - fork with map function in Redux Saga - Stack Overflow

programmeradmin1浏览0评论

I am a beginner at redux-sagas and I am confused with the following situation. I have an items array and I want to fork the same method for each item. So I am using this line of code:

yield items.map(item => fork(loadItemDetails, item));

With the above-mentioned code, loadItemDetails is never invoked. On the contrary, if I call fork individually on each item, as shown below, then it works as intended.

yield fork(loadItemDetails, items[0]);
yield fork(loadItemDetails, items[1]);
yield fork(loadItemDetails, items[2]);

This is confusing me and I can't figure out the reason why the map won't work.

I am a beginner at redux-sagas and I am confused with the following situation. I have an items array and I want to fork the same method for each item. So I am using this line of code:

yield items.map(item => fork(loadItemDetails, item));

With the above-mentioned code, loadItemDetails is never invoked. On the contrary, if I call fork individually on each item, as shown below, then it works as intended.

yield fork(loadItemDetails, items[0]);
yield fork(loadItemDetails, items[1]);
yield fork(loadItemDetails, items[2]);

This is confusing me and I can't figure out the reason why the map won't work.

Share Improve this question edited Mar 25, 2020 at 17:49 norbitrial 15.2k10 gold badges39 silver badges64 bronze badges asked Mar 25, 2020 at 17:43 Raafay AlamRaafay Alam 615 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 7

I came across the same issue.

items.forEach(item => yield fork(loadItemDetails, item));

won't work, as you will get the following error:

A 'yield' expression is only allowed in a generator body.

In order to resolve it, I used yield all

export function* itemDetailsSage() {
  const { items } = yield take(SET_CART_ITEMS);
  yield all(items.map(item => fork(loadItemDetails, item)));
}

It might be a little late but this should work.

for (let i = 0; i < items.length; i++) {
    yield fork(loadItemDetails, items[i]);
}

I believe if you add yield inside of the loop before the fork() and instead of .map() if you use .forEach() then it should work like the other example what you have with separated fork calls.

Try the following:

items.forEach(item => yield fork(loadItemDetails, item));

I hope this helps!

How about using afor of:

for (let item of items) {
    yield fork(loadItemDetails, item);
}
发布评论

评论列表(0)

  1. 暂无评论