Skip to content Skip to sidebar Skip to footer

Why Can't I Use Nested Yield In For..in Loop In Redux-Saga

So I have tasks object with ids and values. With for in loop I want to read 'members' property. If it exist, and first element of array !=='all' I want to make request to firebase

Solution 1:

const fetchedMembers = tasks[task].members.map(member => {
  const user = yield db.collection('users').doc(member).get()
  const userData = user.data()
  return {
    uid: member,
    ...userData
  }
})

The function you pass to .map is not a generator function, so you can't use yield in it. And it can't be a generator function, since map knows nothing about generators or sagas.

One option is to create an array of promises, and then yield that (either wrapped in Promise.all, or redux-saga's all effect):

const promises = tasks[task].members.map(member => {
  return db.collection('users').doc(member).get();
})

const members = yield all(promises);
const fetchedMembers = members.map(user => {
  const userdata = user.data();
  return {
    uid: member,
    ...userData;
  }
);

Another option is to write a mini-saga you want to do for each member, and then create an array of call effects, then yield all of those:

const callEffects = tasks[task].members.map(member => {
  return call(function* () {
    const user = yield db.collection('users').doc(member).get()
    const userData = user.data()
    return {
      uid: member,
      ...userData
    }
  });
})

const fetchedMembers = yield all(callEffects);

Post a Comment for "Why Can't I Use Nested Yield In For..in Loop In Redux-Saga"