Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

A utility to simplify the Redux modular duck pattern

License

NotificationsYou must be signed in to change notification settings

k2p-ed/easy-ducks

Repository files navigation

travis buildLicense: MIT

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.

Installation

yarn add easy-ducks# ornpm install --save easy-ducks

Quick Start

First 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})

Options

Instance Options

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:

NameTypeRequiredDefaultDescription
baseUrlstringtrueThe base url for your api
initialStateobjectfalseThe default value to be passed to the reducer
pluginfunctionfalseAllows for http implementations other thanfetch
storeParamsbooleanfalsefalseTells 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:{}}})

Request Options

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:

NameTypeRequiredDescriptionArguments
actionModifiersobjectfalseAllows for modifying the dispatched action.
onErrorfunctionfalseCallback function for request errorerror,  getState
onSuccessfunctionfalseCallback function for request successsuccess,  getState
paramsobjectfalseContains any parameters to be passed with the request.
resolverfunctionfalseAllows custom handling of responsesstate,  action
verbstringfalseSpecifies an alternate verb to use in the action type. Defaults to the http method, e.g.get,post, etc.

Global configuration

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

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.

ModifierArguments
begingetState
successresponse,  getState
errorerror,  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})})}})

Callbacks

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

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]})})

Plugins

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 theaxios plugin, you must haveaxios installed as a package dependency.
  • If you're usingfetch, query params must be included directly in thepath string.

Writing Plugins

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 API
  • method - e.g.,delete,get,post,put
  • path - The remainder of the request endpoint afterbaseUrl
  • params - An object containing request data

Take a look at the plugins in thesrc/plugins directory for some examples.

Example Project

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

Stars

Watchers

Forks

Packages

No packages published

[8]ページ先頭

©2009-2025 Movatter.jp