Skip to content

Commit

Permalink
feat: create synced actions
Browse files Browse the repository at this point in the history
  • Loading branch information
dhruwlalan committed Mar 5, 2022
1 parent 96c3eaa commit bb1c91d
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 0 deletions.
36 changes: 36 additions & 0 deletions src/createSyncedActions.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { select, race, put, take } from 'redux-saga/effects';

export const createSyncedActions = (actionsObject) => {
const syncedActionsObject = {};

function* syncedAction(sa, actionObject, force) {
const state = yield select(sa.state);
if (!state[sa.success] || force) {
if (!state[sa.loading]) yield put(actionObject);
yield race(sa.race.map((a) => take(a)));
const newState = yield select(sa.state);
if (newState[sa.success]) return true;
if (newState[sa.failure]) return false;
}
return true;
}

Object.keys(actionsObject).forEach((key) => {
syncedActionsObject[key] = syncedAction.bind(null, actionsObject[key]);
});

return {
putSync: function* (actionObject) {
const type = actionObject.type;
const action = syncedActionsObject[type];
if (action) yield syncedActionsObject[type](actionObject, false);
else console.error(`no synced action defined for: ${type}`);
},
putSyncForce: function* (actionObject) {
const type = actionObject.type;
const action = syncedActionsObject[type];
if (action) yield syncedActionsObject[type](actionObject, true);
else console.error(`no synced action defined for: ${type}`);
},
};
};
1 change: 1 addition & 0 deletions src/rega.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,3 +32,4 @@ export const rega = ({ name, initialState, actions }) => {
};

export { createRouterSaga } from './createRouterSaga';
export { createSyncedActions } from './createSyncedActions';

0 comments on commit bb1c91d

Please sign in to comment.