DEV Community

tqm1990
tqm1990

Posted on

redux-saga without redux

This article is based on the blog post that I wrote in Japanese.

This is my first tec article written in English.
I know my article is including a lot of grammar errors but It is one of my challenge.

Why ?

I wanted a concurrent processing like redux-saga but did not want depending on redux.
then, I tried to use redux-saga without redux.

How to do it

redux-saga has runSaga(options, saga, ...args) as a External API which anyone might not know.

The api is used to be called out of a context of redux-saga to run a saga.
see below:
https://redux-saga.js.org/docs/api/

Let's get started to write small code.

// helper.js const sagaOptionSingleton = (() => { let channelStd = stdChannel(); let emitter = new EventEmitter(); emitter.on("action",channelStd.put); return { channel:channelStd, dispatch:output => { emitter.emit("action",output); }, getState:() => {} }; })(); export function runSagaWithFixedOpt(saga){ runSaga(sagaOptionSingleton,saga); } 

One of the important thing is that stdChannel has been given to the option.
I think the API doc does not describe that stdChannel is an interface that is buffering some actions put by a saga in a saga context.
It should be implemented by a singleton pattern.

Therefore, I wrote a self executing function to create the sagaOptionSingleton that is used to set to the option.
Finally, redux-saga did not depend on redux !

for that reason, "put" as a side effect of redux-saga, does not make any effects to the store of redux.
If we want to write something to the store,
we use store.dispatch() .

I got a pure redux !

but, how to notify events from mapDispatchToProps in react-redux ?
It can not do it for that reason.
instead, I am going to write a wrapper function like below:

// helper.js export function sendToSaga(data){ function* sendSomethingToSaga(){ yield put(data); } runSagaWithFixedOpt(sendSomethingToSaga); } 

It is trying to send an event by the way that running a saga out of saga context and doing put action.
then,
I wrote a code for mapDispatchToProps like below:

const mapDispatchToProps = dispatch => { return { increment: () => { sendToSaga({ type: 'INCREMENT' });// Send a event to saga } } } 

Conclusion

We can use redux-saga without redux.

Top comments (0)