Search code examples
redux-sagasaga

Redux saga. How to put action using addEventListener?


How to put action using addEventListener?

Here is example: https://codesandbox.io/s/redux-toolkit-state-new-array-forked-t84l9?file=/src/redux/sagas/sagas.js

function* someFunc() {
// yield put(action)
}

addEventListener('event', *---what's this should be?---*)

Solution

  • Generally, most addEventListener events are connected to some UI so you would just listen for the event in your component and then dispatch an action to get the data into a saga.

    However, in case you really need to listen for some event directly in sagas you can use an eventChannel for that purpose.

    It would end up looking something like this:

    function* someFunc(event) {
        // ...
    }
    
    function* rootSaga() {
        const clickChannel = eventChannel((emitter) => {
            document.addEventListener('click', emitter);
            return () => document.removeEventListener('click', emitter);
        });
        yield takeEvery(clickChannel, someFunc);
    }
    
    

    You can see both the component and direct approach implemented here to test it out: https://codesandbox.io/s/httpsstackoverflowcomquestions67683057redux-saga-how-to-put-action-using-addeventlistener-62rtr?file=/src/index.js:555-884

    I use the component approach to store a name in store and the direct approach to save mouse coordinates.