Merim
Merim

Reputation: 1363

Infinite loop in Redux Saga

I see many questions about this but nothing from answers helps me to solve it. I wanted to see how saga works since I haven't worked with it.

Here is the code

export function* fetchItems() {
  try {
    yield put({ type: ITEMS_FETCH_REQUEST })
    const response = yield call(fetch, 'https://jsonplaceholder.typicode.com/users');
    const data = response.json();
    yield put({ type: ITEMS_FETCH_SUCCESS, payload: { items: data } })
  } catch (error) {
    yield put({ type: ITEMS_FETCH_FAILURE, payload: { error: error.message }})
  }
}

It calls an infinite loop, I tried a lot of things but nothing helps.

What am I doing wrong here ?

Upvotes: 1

Views: 2923

Answers (1)

Merim
Merim

Reputation: 1363

I figured it out, for watchAsyncSagaFunction generator function you need to create another constant that is different than the one that you call at the beginning of asyncSagaFunction.

Example:

export function* asyncSagaFunction() {
  try {
    yield put({ type: ITEMS_FETCH_REQUEST })
    const response = yield call(fetch, 'https://jsonplaceholder.typicode.com/users');
    const data = response.json();
    yield put({ type: ITEMS_FETCH_SUCCESS, payload: { items: data } })
  } catch (error) {
    yield put({ type: ITEMS_FETCH_FAILURE, payload: { error: error.message }})
  }
} 

There is ITEMS_FETCH_REQUEST, you need to create another one, for example,ITEMS_FETCH and in a component call that one.

export function* watchAsyncSagaFunction() {
  yield takeLatest(ITEMS_FETCH, fetchItems)
}

Upvotes: 3

Related Questions