Last active
November 6, 2018 02:40
-
-
Save jdoleary/64cce4036662a820ed55d3f0464df351 to your computer and use it in GitHub Desktop.
Faux Implementation of Redux-Saga
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
The following is a fake implementation of functions inside of Redux-Saga. | |
*/ | |
// Simplistic fake implementations of Saga Effects | |
const put = action => ({effect:'PUT', action}); | |
const call = fn => ({effect:'CALL', fn}); | |
// Simplistic fake implementation of runSaga | |
function runSaga(genFn, ...args){ | |
const gen = genFn(...args); | |
let next = gen.next(); | |
while(!next.done){ | |
const {effect, action, fn} = next.value; | |
switch(effect){ | |
case 'PUT': | |
dispatch(action); | |
next = gen.next(action); | |
break; | |
case 'CALL': | |
next = gen.next(fn()); | |
break; | |
} | |
} | |
} | |
// Fake Redux dispatch | |
function dispatch(action){ | |
console.log(`Dispatching ${JSON.stringify(action)}`); | |
} | |
/* | |
The rest of the code in this gist is code that you would supply to make use of the Redux-Saga functions above | |
*/ | |
// Make a saga | |
function* mySaga(value){ | |
yield put({type:'FIRST_ACTION', value}); | |
const active = yield call(isActive); | |
if(active){ | |
yield put({type:'ACTIVE_ACTION'}); | |
}else{ | |
yield put({type:'WONT_BE_DISPATCHED'}); | |
} | |
} | |
// helper for demonstration purposes | |
function isActive(){ | |
return true; | |
} | |
// Run the saga! | |
runSaga(mySaga, 123); | |
/* | |
Running this code will output: | |
Dispatching {"type":"FIRST_ACTION","value":123} | |
Dispatching {"type":"ACTIVE_ACTION"} | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment