0

The fetchBooks generator function takes the action and fetches books per the category specified.

function* fetchBooks() {
  while (true) {
    const { payload:{ bookCategory }} = yield take(FETCH_BOOKS);
    // receive and perform external fetch
    const books = fetchMyBooks(bookCategory);

    !books
      ? yield put({ type: FAILURE })
      : yield books
  }
}

Inside another generator function I am trying to call fetchBooks like so

function* handleSomethingAndThenFetch() {
  // ...doing soemthing... then
  const books = yield put({ type: fetchBooks, payload:{ 'FICTION' }});

}

Using the fetchBooks generator function, how can I return the value of the books? I tried using this:

const books = yield call(fetchBooks, 'FICTION');

but I am trying to avoid changing the fetchBooks books function. Is there another way?

M.Holmes
  • 403
  • 1
  • 7
  • 22

1 Answers1

0

This is inconsistent:

!books
      ? yield put({ type: FAILURE })
      : yield books

It should instead be something like:

!books
      ? yield put({ type: FAILURE })
      : yield put({ type: FETCH_BOOKS_SUCCESS, books})

Then your handleSomethingAndThenFetch would become:

function* handleSomethingAndThenFetch() {
  // ...doing soemthing... then
  yield put({ type: fetchBooks, payload:{ 'FICTION' }});

  const {failure, success} = race({
    success: take(FETCH_BOOKS_SUCCESS),
    failure: take(FAILURE)
  });

  if (success) {
    const { books } = success
    // do something with fetched books
  } else if (failure) {
    // Handle failure
  }
}

This is all assuming you really want fetchBooks to be exposed and listening to the FETCH_BOOKS actions. A better approach IMHO is to just wrap the API calling part in a separate saga that is not connected to redux actions. fetchBooks become:

function* fetchBooks(bookCategory) {
  return yield call('fetchMyBooks', bookCategory);
}

Then just use that saga directly from your other sagas:

function* handleSomethingAndThenFetch() {
  // ...doing soemthing... then
  const books = yield fetchBooks('FICTION');

Much simpler.

Amr Mostafa
  • 23,147
  • 2
  • 29
  • 24