Raafay Alam
Raafay Alam

Reputation: 61

fork with map function in Redux Saga

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.

Upvotes: 3

Views: 1254

Answers (4)

Luillyfe
Luillyfe

Reputation: 6842

How about using afor of:

for (let item of items) {
    yield fork(loadItemDetails, item);
}

Upvotes: 0

Mert Simsek
Mert Simsek

Reputation: 698

It might be a little late but this should work.

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

Upvotes: 2

Keren
Keren

Reputation: 91

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)));
}

Upvotes: 7

norbitrial
norbitrial

Reputation: 15166

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!

Upvotes: 0

Related Questions