redux-async
Async function wrapper for Redux powered by Redux-Saga
Install
npm i @weavedev/redux-async
API documentation
We generate API documentation with TypeDoc.
Usage
Creating
In this example we create a reducer, saga and actions from an async function. This async function triggers its callback after 3 seconds.
import { ReduxAsync } from '@weavedev/redux-async';
const START_ACTION = 'START_ACTION';
const DONE_ACTION = 'DONE_ACTION';
const FAIL_ACTION = 'FAIL_ACTION';
export const asyncResource = new ReduxAsync(START_ACTION, DONE_ACTION, FAIL_ACTION, async (name: string): Promise<string> => {
// This promise waits 3 seconds and then returns
return new Promise((resolve: ((value: string) => void)): void => {
setTimeout(() => {
resolve(`Hey, ${name}!`);
}, 3000);
});
});
// If you are also using our store package (@weavedev/store)
window.storeReducers.asyncResource = asyncResource.reducer;
window.storeSagas.asyncResource = asyncResource.saga;
declare global {
interface StoreReducersMap {
asyncResource: typeof asyncResource.reducer;
}
interface StoreActionsMap {
asyncResource: typeof asyncResource.actions;
}
}
Triggering
You can run your async function by calling .run()
. The argument types will match those of your async function.
import { asyncResource } from './asyncResource';
// If you are also using our store package (@weavedev/store)
window.store.dispatch(asyncResource.run('Dave'));
Use inside a saga
You can run and wait for results from your async function by passing .runSaga
to redux-saga
's call()
effect. The argument types will match those of your async function. This can be useful when you need to run multiple async tasks in order.
function* mySaga(): Iterator<any> {
const result = yield call(asyncResource.runSaga, 'Laura');
console.log("resource returned", result);
}
Types
You can access the types of the actions, reducer, saga and state by using typeof
// All actions
type MyActions = typeof asyncResource.actions;
// Trigger action
type MyTriggerAction = typeof asyncResource.actionMap.trigger;
// Callback action
type MyCallbackAction = typeof asyncResource.actionMap.callback;
// Error action
type MyErrorAction = typeof asyncResource.actionMap.error;
// Reducer
type MyReducer = typeof asyncResource.reducer;
// Reducer
type MySaga = typeof asyncResource.saga;
// State
type MyState = typeof asyncResource.state;
License
Made by Paul Gerarts and Weave