janhartmann
janhartmann

Reputation: 15003

Dispatch action every X second using Redux Saga

Being completely new to redux-saga, I am trying to set up a saga which reacts on action LANGUAGE_START_CYCLE and cycles the action LANGUAGE_CYCLE every 3 second.

But the saga LANGUAGE_CYCLE is never run as I would expect when I dispatch LANGUAGE_START_CYCLE to the Redux store.

Any idea what I am doing wrong? I would suspect it being a simple mistake as my other sagas are running just fine.

// constants/ActionTypes.js
export const LANGUAGE_SET_ACTIVE = "LANGUAGE_SET_ACTIVE";
export const LANGUAGE_START_CYCLE = "LANGUAGE_START_CYCLE";
export const LANGUAGE_STOP_CYCLE = "LANGUAGE_STOP_CYCLE";
export const LANGUAGE_CYCLE = "LANGUAGE_CYCLE";


// actions/language.js
export const cycleLanguage = () => {
    return {
        type: ActionTypes.LANGUAGE_CYCLE
    }
};    

// languageSaga.js
import { actionChannel, call, take, put, race } from 'redux-saga/effects'
import * as ActionTypes from '../constants/ActionTypes';
import * as actions from '../actions/language';

const wait = ms => {
    new Promise(resolve => {
        setTimeout(() => resolve(), ms)
    })
};

export default function * languageSaga() {
    const channel = yield actionChannel(ActionTypes.LANGUAGE_START_CYCLE);
    while (yield take(channel)) {
        while (true) {
            const { stopped } = yield race({
                wait: call(wait, 3000),
                stopped: take(ActionTypes.LANGUAGE_STOP_CYCLE)
            });

            if (!stopped) {
                yield put(actions.cycleLanguage());
            } else {
                break;
            }
        }
    }
}


// sagas.js (root sagas)
export default function * sagas() {
    yield [
        directorySaga(), // Another saga which works fine
        pusherSaga(), // Another saga which works fine
        languageSaga()
    ]
}

Example of one of my other sagas, which are working:

// directorySaga.js
function * fetchDirectory(action) {
    try {
        const directory = yield call(Api.fetchDirectory, action.id);
        yield put(fetchDirectorySucceeded(directory));
    } catch (e) {
        yield put(fetchDirectoryFailed(e.message));
    }
}

export default function * directorySaga() {
    yield * takeLatest(ActionTypes.DIRECTORY_REQUESTED, fetchDirectory);
}

Upvotes: 3

Views: 4091

Answers (2)

Developer Guru
Developer Guru

Reputation: 85

I think the wait function is wrong type. you have to fix like this.

const wait = ms => {
  return new Promise(resolve => {  
    setTimeout(() => resolve(), ms)  
  })
}

Upvotes: 0

janhartmann
janhartmann

Reputation: 15003

I am going to answer my question here.

The above code i working, but when I was triggering the actions, I was using Redux Dev Tools to dispatch actions to the store.

I manually dispatched LANGUAGE_START_CYCLE using the tools, which changed the state - but apparently this did not notify the saga middle-ware and my channel was never updated:

Redux Dev Tools dispatching

But when using a simple button in one of my components:

<button onClick={() => dispatch(actions.startCycle())}>
    Start
</button>
<button onClick={() => dispatch(actions.stopCycle())}>
    Stop
</button>

The saga middle-ware was notified.

UPDATE

My store configuration is:

import { createStore, applyMiddleware, compose } from 'redux'
import createSagaMiddleware from 'redux-saga';
import rootReducer from '../reducers/index';
import sagas from '../sagas/index';

export default function configureStore(initialState) {
  const sagaMiddleware = createSagaMiddleware();
  const store = createStore(rootReducer, initialState, compose(
    applyMiddleware(sagaMiddleware),
    window.devToolsExtension ? window.devToolsExtension() : f => f
  ));

  if (module.hot) {
    // Enable Webpack hot module replacement for reducers
    module.hot.accept('../reducers', () => {
      const nextReducer = require('../reducers');
      store.replaceReducer(nextReducer);
    });
  }

  sagaMiddleware.run(sagas);

  return store;
}

Upvotes: 1

Related Questions