Skip to content
Advertisement

Polling with redux-saga

I tried to solve polling with the information on this page: https://bigbite.net/polling-with-redux/

// inside a saga
import { delay } from 'redux-saga';
...

export function* pollStuffSaga() {
  while (true) {
    try {
      const response = yield call(fetchStuff);
      const items = handleResponse(response);
      yield put(onFetchStuffSuccess(items));
      yield delay(30000); // 30 sec
    } catch (e) {
      yield put(onFetchStuffFailure(e));
    }
  }
}

function* pollWatcherSaga() {
  while (true) {
    yield take(START_POLLING); // I call start polling from componentDidMount
    yield race([call(pollArchiveSaga), take(STOP_POLLING)]); // And I call stop polling from componentWillUnmount
  }
}

export default function* rootSaga() {
  yield call(pollWatcherSaga); // fired when saga is injected
}

The problem I have now is that I see in network that my service gets called too many times. It is called all the time. Should not my delay prevent it to call my fetchStuff in the next round inside while? Should it not wait for 30 sec before the code moves on?

Advertisement

Answer

I have made a comment on the line which was the problem. When I fixed my “homemade method”, handleResponse(response), then my pulling logic worked. So just look away for how I handle my response inside that method, and this code will work with corresponding reducer and actions etc:

import { delay } from 'redux-saga';
...

export function* pollStuffSaga() {
  while (true) {
    try {
      const response = yield call(fetchStuff);
      const items = handleResponse(response); // The problem was inside this function
      yield put(onFetchStuffSuccess(items));
      yield delay(30000);
    } catch (e) {
      yield put(onFetchStuffFailure(e));
    }
  }
}

function* pollWatcherSaga() {
  while (true) {
    yield take(START_POLLING);
    yield race([call(pollArchiveSaga), take(STOP_POLLING)]);
  }
}

export default function* rootSaga() {
  yield call(pollWatcherSaga);
}
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement