Redux-saga: Yield in forEach loop

Created on 21 Sep 2016  路  3Comments  路  Source: redux-saga/redux-saga

My problem is similar to #551 but the channel solution doesn't seem appropriate for me.

My need is to call a fetch function that receives an array of URLs, and then iterate through the URLs with additional fetch requests. It seems to me that a forEach loop with a yield inside would achieve this:

let newArray = [];

fetchedArray.content.forEach((item) => {
  const toAdd = yield call(auth.get, item.url, token);
  toAdd.push(newArray);
});

However this errors immediately. Is there a method for initiating a fetch request from an unknown number of URLs using yield?

Many thanks.

Most helpful comment

Found a solution - by changing the structure and switching to a map, the yields seem to work perfectly:

const newArray = yield array.content.map((item) => call(auth.get, item.url, token));

Hope this helps someone else.

All 3 comments

Found a solution - by changing the structure and switching to a map, the yields seem to work perfectly:

const newArray = yield array.content.map((item) => call(auth.get, item.url, token));

Hope this helps someone else.

yes @tobyl , you can also use a regular javascript loop instead of a foreach for imperative style login, as we stay in the generator execution context.

foreach does not work, but it would probably be simply to create an util to emulate it.

Note that if only one promise fail, you won't get a newArray at all

Thanks @slorber - that actually works well for me, since I can do response/error as though it were one call rather than having to handle each and then partially handle data.

Thanks!

Was this page helpful?
0 / 5 - 0 ratings