redux-promise-dispatch
A straightforward yet flexible wrapper for asynchronously generating redux actions. redux-promise-dispatch
dispatches actions at the beginning and successful completion (resolve
) or failure (reject)
of a promise.
For example, the start, or request
action, is fired when you first call the action creator. This can be used for tasks like marking a fetching
flag as true
.
The success
action is dispatched when the promise resolves, and the failure
action is dispatched if the promise rejects. The result of your promise as well as any arguments passed into the original
Examples
Super Basic Usage
You're going to need exactly four things.
-
A function that returns a promise.
-
Three action creators
- One to dispatch before the promise starts (
request
) - One to dispatch when the promise resolves/succeeds (
success
) - One to dispatch when the promise rejects/fails (
failure
)
// Something that returns a promiseconst timedPromise = { return { }} // Redux actions for promise start/success/failureconst startingPromise = type: "PROMISE_START"const successfulPromise = type: "PROMISE_SUCCESS"const failedPromise = type: "PROMISE_FAILURE" // Define the wrapped promise (secretly just a thunk)const yourAction = // Dispatch the wrapped action to redux// Dispatches the start action, starts the promise,// dispatches success/failure actions as needed // In this example only the action types make it to the reducer
Basic Usage
Okay, that was really boring, and we didn't even touch on what promiseDispatcher
does with arguments. This example will show you how to pass arguments and use them throughout the lifecycle of your promise and its results.
Now we're going to make some changes
- Have the promise returning function (
promiseToExecute
) to take a value. - Have the initial action (
request
) also use the value passed topromiseToExecute
. - Have the success action (
success
) use the results ofresolve
. - Have the failure action (
failure
) use the results ofreject
. - We're also going to pass the value we gave
promiseToExecute
when we call the wrapped action.
// Take some arguments, return a promiseconst promiseToExecute = { return { }} // Action creator with the same arguments as the above functionconst promiseStarted = type: "PROMISE_START" payload: value // Action creator that takes the result of promise successconst promiseResolved = type: "PROMISE_SUCCESS" payload: result // Action creator that takes the result of promise failureconst promiseRejected = type: "PROMISE_FAILURE" payload: result // Define the wrapped promiseconst actionToExecute = // Dispatch to redux, provide the starting arguments // promiseStarted --> action.payload = 2 // promiseResolved --> action.payload = "2 is even!"
License
MIT