- Notifications
You must be signed in to change notification settings - Fork0
A utility to simplify the Redux modular duck pattern
License
k2p-ed/easy-ducks
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
Easy Ducks is a utility that simplifies the implementation of theducks pattern for async actions in Redux. It eliminates the need to manually create reducers (no more switch statements!) or action types, and greatly simplifies action creators.
Easy Ducks automatically handles loading states by addingloading anddidLoad keys to each reducer. When a request is in progress,loading will be true, and when a request has previously completed at some point,didLoad is set to true. This can be useful if you want to show a different loading state for when there is some pre-existing data, versus the initial load with no data.
By default, Easy Ducks adds async responses to the reducer by with object spread notation, e.g.,
(state,action)=>({ ...state, ...action.response})
You can override this by providingresolver functions to action creators in order to define custom behavior.
Easy Ducks assumes you're usingredux-thunk middleware in your project.
The default configuration relies on thefetch API, so you may need to provide a polyfill for extended browser support. Alternatively, you can use plugins to support other http implementations.
yarn add easy-ducks# ornpm install --save easy-ducksFirst create your duck and export the reducer:
// ducks/users.jsimport{Duck}from'easy-ducks'constduck=newDuck('myDuck',{baseUrl:'https://myapi.com/api'})// Pass this to redux's combineReducers functionexportdefaultduck.reducer// Action creatorsexportconstgetUser=id=>duck.get(`/users/${id}`)exportconstcreateUser=(params={})=>duck.post('/users',{ params})exportconsteditUser=(id,params={})=>duck.put(`/users/${id}`,{ params})exportconstdeleteUser=id=>duck.delete(`/users/:id`)
Then add the exportedduck.reducer to your root reducer:
// ducks/index.jsimport{combineReducers}from'redux'importusersfrom'./users'exportdefaultcombineReducers({ users})
The first constructor argument is a string indicating the name of the duck. The name is used to assemble the Redux action type, so itmust be unique.
The format for the generated action types looks like this:
[{name}] {method}: {status}
For example, if you create a duck with the namemyDuck, the actions forduck.get() would look like this:
// GET begin{type:'[myDuck] GET: BEGIN'}// GET error{type:'[myDuck] GET: ERROR', error}// GET success{type:'[myDuck] GET: SUCCESS', response}
The second constructor argument is an instance configuration object:
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
| baseUrl | string | true | The base url for your api | |
| initialState | object | false | The default value to be passed to the reducer | |
| plugin | function | false | Allows for http implementations other thanfetch | |
| storeParams | boolean | false | false | Tells Easy Ducks to save any params passed to a request in the reducer |
As an alternative tostoreParams, you can include aparams object in theinitialState:
constduck=newDuck('myDuck',{baseUrl:'https://myapi.com/api',initialState:{params:{}}})
The first request argument ispath, which is a string that indicates the remainder of the request URL after thebaseUrl provided in the constructor.
The second request argument is an optional configuration object:
| Name | Type | Required | Description | Arguments |
|---|---|---|---|---|
| actionModifiers | object | false | Allows for modifying the dispatched action. | |
| onError | function | false | Callback function for request error | error, getState |
| onSuccess | function | false | Callback function for request success | success, getState |
| params | object | false | Contains any parameters to be passed with the request. | |
| resolver | function | false | Allows custom handling of responses | state, action |
| verb | string | false | Specifies an alternate verb to use in the action type. Defaults to the http method, e.g.get,post, etc. |
This package provides a named export calledDuckFactory to simplify re-use of configuration values across all duck instances.
// duckFactory.jsimport{DuckFactory}from'easy-ducks'importpluginfrom'utils/myPlugin'constduckFactory=newDuckFactory({baseUrl:'https://my-api.com/api', plugin})exportdefaultduckFactory
Now import this instance into your individual duck files and create new ducks from that. Ducks created using this method will inherit any configuration options that you previously specified.
importduckFactoryfrom'../duckFactory'constduck=duckFactory.create('users')exportdefaultduck.reducerexportconstgetUsers=()=>duck.get('/users')
Action modifiers are functions that allow you to modify the object that is passed to thedispatch function. You can provide a modifier for each of the three statuses:begin,success, anderror.
| Modifier | Arguments |
|---|---|
| begin | getState |
| success | response, getState |
| error | error, getState |
This functionality can be useful if you're using some type of redux analytics middleware, such asredux-segment to track events based on redux actions.
In this example, theanalytics key would be added to the object passed todispatch:
constfetchUser=id=>duck.get(`/users/${id}`,{actionModifiers:{success:(response)=>({meta:trackEvent('viewed user',{ id,name:response.name})})}})
The dispatch function returns a promise, so if you want to perform actions after the request's success or failure you can do so inside a.then block.
For example, if you wanted to save a response to local storage on success:
importlocalStoragefrom'store'store.dispatch(fetchUser(1)).then((response)=>{localStorage.set('user',response)})
Sometimes you may want to perform some action inside the action creator itself. For this scenario there are two optional callbacks,onSuccess andonError. These callbacks receiveresponse anderror, respectively, as arguments.
Using these callbacks, the example above would look like this:
exportconstfetchUser=id=>duck.get(`/users/${id}`,{onSuccess:(response)=>{localStorage.set('user',response)}})
Resolvers are functions that allow you to define custom behavior for updating the store. Resolvers take the same arguments as the reducer itself,state andaction, and return the new state on request success.
For example, if a reducer contains an array of users, and you want to add the new user object returned by yourcreateUser action creator, you can define a resolver that adds it to the end of the array.
exportconstcreateUser=(params={})=>duck.post('/something',{ params,resolver:(state,action)=>({ ...state,users:[...state.users,action.response.user]})})
Easy Ducks usesfetch by default to make http requests, but you can provide plugins if you'd like to use something else. Plugins foraxios andfetch are included with the library.
importaxiosPluginfrom'easy-ducks/lib/plugins/axios'constplugin=axiosPlugin()constduck=newDuck('myDuck',{baseUrl:'https://myapi.com/api', plugin})
You can also provide a configuration object to plugin which will be passed along to the config options for the http solution.
constplugin=axiosPlugin({headers:{Authentication:'my-auth-token'}})
Sincefetch is used by default, you only need to explicitly provide thefetch plugin if you want to pass it a custom configuration object.
Notes:
- If you're using the
axiosplugin, you must haveaxiosinstalled as a package dependency. - If you're using
fetch, query params must be included directly in thepathstring.
Plugins are simply functions that take an object and map the values to the http library of your choice. The object keys are:
baseUrl- The base URL of your APImethod- e.g.,delete,get,post,putpath- The remainder of the request endpoint afterbaseUrlparams- An object containing request data
Take a look at the plugins in thesrc/plugins directory for some examples.
This repo includes an example project that you can run to test out the library in action.
# Install dependenciesyarn# Start the dev serveryarn start
Then go tolocalhost:7000 to view the example project.
About
A utility to simplify the Redux modular duck pattern
Topics
Resources
License
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Packages0
Uh oh!
There was an error while loading.Please reload this page.