1.0.0 • Published 3 years ago

fahad-redux-axios-midleware v1.0.0

Weekly downloads
3
License
MIT
Repository
github
Last release
3 years ago

redux-axios-middleware

npm version

Redux middleware for fetching data with axios HTTP client

Installation

npm i -S redux-axios-middleware

You can also use in browser via <script src="https://unpkg.com/redux-axios-middleware/dist/bundle.js"></script>, the package will be available under namespace ReduxAxiosMiddleware

How to use?

Use middleware

By default you only need to import middleware from package and add it to redux middlewares and execute it with first argument being with axios instance. second optional argument are middleware options for customizing

import {createStore, applyMiddleware} from 'redux';
import axios from 'axios';
import axiosMiddleware from 'redux-axios-middleware';

const client = axios.create({ //all axios can be used, shown in axios documentation
  baseURL:'http://localhost:8080/api',
  responseType: 'json'
});

let store = createStore(
  reducers, //custom reducers
  applyMiddleware(
    //all middlewares
    ...
    axiosMiddleware(client), //second parameter options can optionally contain onSuccess, onError, onComplete, successSuffix, errorSuffix
    ...
  )
)

Dispatch action

Every action which have payload.request defined will be handled by middleware. There are two possible type definitions.

  • use action.type with string name
  • action with type will be dispatched on start, and then followed by type suffixed with underscore and
  • success suffix on success, or error suffix on error

defaults: success suffix = "_SUCCESS" error suffix = "_FAIL"

export function loadCategories() {
  return {
    type: 'LOAD',
    payload: {
      request:{
        url:'/categories'
      }
    }
  }
}
  • use action.types with array of types [REQUEST,SUCCESS,FAILURE]
  • REQUEST will be dispatched on start, then SUCCESS or FAILURE after request result
export function loadCategories() {
  return {
    types: ['LOAD','AWESOME','OH_NO'],
    payload: {
      request:{
        url:'/categories'
      }
    }
  }
}

Actions that are handled by this middleware return a promise. This gives you the ability to chain actions. A good example of this might be a form. In the form you might dispatch an actions to store the form values. The normal flow of the action into the reducers would not be altered but you can chain a then/catch onto the initial dispatch.

this.props.saveForm(formData)
  .then(() => {
    // router the user away
    this.context.router.push("/my/home/page")
  })
  .catch((response) => {
    //handle form errors
  })

Another example might be a set of actions that you want dispatched together.

Promise.all([
  dispatch(foo()),
  dispatch(bar()),
  dispatch(bam()),
  dispatch(boom())

]).then(() => {
  dispatch(
    loginSuccess(
      token
    )
  )
})

Request complete

After request complete, middleware will dispatch new action,

on success

{
  type: 'AWESOME', //success type
  payload: { ... } //axios response object with data status headers etc.
  meta: {
    previousAction: { ... } //action which triggered request
  }
}

on error

Error action is same as success action with one difference, there's no key payload, but now there's error;

{
    type:'OH_NO',
    error: { ... }, //axios error object with message, code, config and response fields
    meta: {
      previousAction: { ... } //action which triggered request
    }
}

if axios failed fatally, default error action with status 0 will be dispatched.

{
    type:'OH_NO',
    error: {
      status: 0,
      ... //rest of axios error response object
    },
    meta: {
      previousAction: { ... } //action which triggered request
    }
}

Multiple clients

If you are using more than one different APIs, you can define those clients and put them to middleware. All you have to change is import of middleware, which is passed to redux createStore function and defined those clients.

import { multiClientMiddleware } from 'redux-axios-middleware';
createStore(
 ...
 multiClientMiddleware(
   clients, // described below
   options // optional, this will be used for all middleware if not overriden by upper options layer
 )
)

clients object should be map of

{
  client: axiosInstance, // instance of axios client created by axios.create(...)
  options: {} //optional key for passing specific client options
}

For example:

{
  default: {
    client: axios.create({
       baseURL:'http://localhost:8080/api',
       responseType: 'json'
    })
  },
  googleMaps: {
    client: axios.create({
        baseURL:'https://maps.googleapis.com/maps/api',
        responseType: 'json'
    })
  }
}

Now in every dispatched action you can define client used:

export function loadCategories() {
  return {
    type: 'LOAD',
    payload: {
      client: 'default', //here you can define client used
      request:{
        url:'/categories'
      }
    }
  }
}

If you don't define client, default value will be used. You can change default client name in middleware options.

Middleware options

Options can be changed on multiple levels. They are merged in following direction:

default middleware values < middleware config < client config < action config

All values except interceptors are overriden, interceptors are merged in same order. Some values are changeable only on certain level (can be seen in change level column).

Legend: M - middleware config C - client config A - action config

keytypedefault valuechange leveldescription
successSuffixstringSUCCESSM C Adefault suffix added to success action, for example {type:"READ"} will be {type:"READ_SUCCESS"}
errorSuffixstringFAILM C Asame as above
onSuccessfunctiondescribed aboveM C Afunction called if axios resolve with success
onErrorfunctiondescribed aboveM C Afunction called if axios resolve with error
onCompletefunctiondescribed aboveM C Afunction called after axios resolve
returnRejectedPromiseOnErrorboolfalseM C Aif true, axios onError handler will return Promise.reject(newAction) instead of newAction
isAxiosRequestfunctionfunction check if action contain action.payload.requestMcheck if action is axios request, this is connected to getRequestConfig
getRequestConfigfunctionreturn content of action.payload.requestM C Aif isAxiosRequest returns true, this function get axios request config from action
getClientNamefunctionreturns action.payload.client OR 'default'M C Aattempts to resolve used client name or use defaultClientName
defaultClientNameevery possible object key type'default'Mkey which define client used if getClienName returned false value
getRequestOptionsfunctionreturn action.payload.optionsM Creturns options object from action to override some values
interceptorsobject {request: [], response: []}M CYou can pass axios request and response interceptors. Take care, first argument of interceptor is different from default axios interceptor, first received argument is object with getState, dispatch and getAction keys

interceptors

interceptors can be added to the middleware 2 different ways: Example:

  const middlewareConfig = {
    interceptors: {
      request: [
        function ({getState, dispatch, getSourceAction}, req) {
          console.log(req); //contains information about request object
          //...
        },
        function ({getState, dispatch, getSourceAction}, req) {
          //...
        }
      ],
      response: [
        function ({getState, dispatch, getSourceAction}, req) {
          console.log(req); //contains information about request object
          //...
        },
        function ({getState, dispatch, getSourceAction}, req) {
          //...
        }
      ]
    }
  };

In example above if request and\or response succeeded interceptors will be invoked. To set interceptors what will handle error on request or response pass an object to request and\or response arrays with corresponding success and\or error functions.

Example:

  const middlewareConfig = {
    interceptors: {
      request: [{
        success: function ({getState, dispatch, getSourceAction}, req) {
          console.log(req); //contains information about request object
          //...
          return req;
        },
        error: function ({getState, dispatch, getSourceAction}, error) {
          //...
          return response
        }
      }
      ],
      response: [{
        success: function ({getState, dispatch, getSourceAction}, res) {
          console.log(res); //contains information about request object
          //...
          return Promise.resolve(res);
        },
        error: function ({getState, dispatch, getSourceAction}, error) {
          return Promise.reject(error);
        }
      }
      ]
    }
  };

Finally, to include the middlewareConfig here is the relevant part of the example copied from the top of this file.

let store = createStore(
  reducers, //custom reducers
  applyMiddleware(
    //all middlewares
    ...
    axiosMiddleware(client,middlewareConfig),
    ...
  )
)

Examples

License

This project is licensed under the MIT license, Copyright (c) 2016 Michal Svrček. For more information see LICENSE.md.

Acknowledgements

Dan Abramov for Redux Matt Zabriskie for Axios. A Promise based HTTP client for the browser and node.js

acornacorn-dynamic-importalign-textajvacorn-jsxajv-keywordsansi-escapesansi-stylesansi-regexanymatchargparsearr-diffarr-unionarr-flattenarray-unionarray-uniqarray-uniqueasn1.jsarrifyassertassertion-errorasyncassign-symbolsasync-eachatobbabel-code-framebabel-corebabel-generatorbabel-helper-bindify-decoratorsbabel-helper-call-delegatebabel-helper-builder-binary-assignment-operator-visitorbabel-helper-define-mapbabel-helper-explode-assignable-expressionbabel-helper-function-namebabel-helper-explode-classbabel-helper-get-function-aritybabel-helper-hoist-variablesbabel-helper-optimise-call-expressionbabel-helper-regexbabel-helper-remap-async-to-generatorbabel-helper-replace-supersbabel-messagesbabel-helpersbabel-plugin-check-es2015-constantsbabel-plugin-syntax-async-generatorsbabel-plugin-syntax-async-functionsbabel-plugin-syntax-class-propertiesbabel-plugin-syntax-class-constructor-callbabel-plugin-syntax-decoratorsbabel-plugin-syntax-dynamic-importbabel-plugin-syntax-export-extensionsbabel-plugin-syntax-exponentiation-operatorbabel-plugin-syntax-object-rest-spreadbabel-plugin-syntax-trailing-function-commasbabel-plugin-transform-async-generator-functionsbabel-plugin-transform-async-to-generatorbabel-plugin-transform-class-constructor-callbabel-plugin-transform-class-propertiesbabel-plugin-transform-decoratorsbabel-plugin-transform-es2015-arrow-functionsbabel-plugin-transform-es2015-block-scoped-functionsbabel-plugin-transform-es2015-block-scopingbabel-plugin-transform-es2015-classesbabel-plugin-transform-es2015-computed-propertiesbabel-plugin-transform-es2015-destructuringbabel-plugin-transform-es2015-for-ofbabel-plugin-transform-es2015-duplicate-keysbabel-plugin-transform-es2015-function-namebabel-plugin-transform-es2015-literalsbabel-plugin-transform-es2015-modules-commonjsbabel-plugin-transform-es2015-modules-amdbabel-plugin-transform-es2015-modules-systemjsbabel-plugin-transform-es2015-modules-umdbabel-plugin-transform-es2015-object-superbabel-plugin-transform-es2015-parametersbabel-plugin-transform-es2015-shorthand-propertiesbabel-plugin-transform-es2015-spreadbabel-plugin-transform-es2015-sticky-regexbabel-plugin-transform-es2015-template-literalsbabel-plugin-transform-es2015-typeof-symbolbabel-plugin-transform-es2015-unicode-regexbabel-plugin-transform-export-extensionsbabel-plugin-transform-exponentiation-operatorbabel-plugin-transform-object-rest-spreadbabel-plugin-transform-regeneratorbabel-plugin-transform-strict-modebabel-polyfillbabel-preset-es2015babel-preset-es2016babel-registerbabel-preset-es2017babel-preset-stage-2babel-preset-stage-3babel-runtimebabel-templatebabel-traversebabel-typesbabylonbasebalanced-matchbase64-jsbig.jsbinary-extensionsbn.jsbrace-expansionbracesbrorandbrowserify-aesbrowserify-cipherbrowserify-desbrowserify-signbrowserify-rsabrowserify-zlibbufferbuffer-xorbuiltin-modulescaller-pathbuiltin-status-codescache-basecallsitescamelcasecenter-alignchalkcipher-basechokidarcircular-jsonclass-utilscli-cursorcli-widthcliuicode-point-atcocollection-visitcommandercommondircomponent-emitterconcat-mapconcat-streamconsole-browserifyconstants-browserifycontains-pathcopy-descriptorcore-jscore-util-iscreate-ecdhcreate-hashcreate-hmaccrypto-browserifydconvert-source-mapdecamelizedebugdeep-eqldecode-uri-componentdeep-equaldeep-isdefine-propertydeldes.jsdetect-indentdiffdoctrinedomain-browserdiffie-hellmanellipticemojis-listenhanced-resolveerrnoes5-exterror-exes6-mapes6-iteratores6-setes6-symboles6-weak-mapescape-string-regexpescopeeslint-import-resolver-nodeesprimaespreeesrecurseestraverseesutilsevent-emittereventsevp_bytestokeyexpand-bracketsexit-hookexpand-rangeextend-shallowextglobfile-entry-cachefiguresfilename-regexfind-cache-dirfill-rangeflat-cachefind-upfollow-redirectsfor-infor-ownformatiofragment-cachefs.realpathfs-readdir-recursivefunction-bindgenerate-functiongenerate-object-propertyget-caller-fileget-valueglobglob-baseglob-parentglobalsglobbygraceful-fsgraceful-readlinkgrowlhashas-ansihas-flaghas-valuefast-levenshteinhas-valueshash-basehash.jshmac-drbghome-or-tmphosted-git-infoieee754ignoreimurmurhashinheritsinflightinquirerhttps-browserifyinterpretinvariantis-accessor-descriptorinvert-kvis-binary-pathis-arrayishis-bufferis-core-moduleis-data-descriptoris-descriptoris-dotfileis-equal-shallowis-extendableis-finiteis-extglobis-fullwidth-code-pointis-globis-my-json-validis-numberis-path-cwdis-path-in-cwdis-path-insideis-plain-objectis-posix-bracketis-primitiveis-propertyis-resolvableis-utf8isarrayis-windowsjadeisobjectjs-tokensjs-yamljsescjson-loaderjson-stable-stringifyjson5jsonifyjsonpointerkind-oflazy-cachelcidlevnload-json-fileloader-runnerloader-utilslodashlodash-eslodash.assignlodash.condlodash.endswithlodash.findlodash.findindexlodash.pickbylolexlongestloose-envifymap-cachelru-cachemap-visitmemory-fsmd5.jsmicromatchminimalistic-assertminimalistic-crypto-utilsmiller-rabinminimatchminimistmixin-deepmkdirpmsmute-streamnanomatchneo-asyncnode-libs-browsernormalize-package-datanumber-is-nannormalize-pathobject-assignobject-copyobject-visitobject.omitobject.pickonceonetimeoptionatoros-browserifyos-homediros-localeoutput-file-syncos-tmpdirparse-asn1pakoparse-globparse-jsonpascalcasepath-browserifypath-dirnamepath-existspath-is-absolutepath-is-insidepath-parsepath-typepbkdf2pifypicomatchpinkie-promisepinkiepkg-dirpkg-uppluralizeposix-character-classespreserveprelude-lsprivateprocessprocess-nextick-argsprogressprrpublic-encryptpunycodequerystringquerystring-es3randomaticrandomfillrandombytesread-pkgread-pkg-upreadable-streamreaddirpreadline2regenerateregenerator-runtimeregenerator-transformregex-cacheregex-notregexpu-coreregjsgenregjsparserremove-trailing-separatorrepeat-elementrepeat-stringrepeatingrequire-directoryrequire-main-filenamerequire-uncachedresolveresolve-fromresolve-urlrestore-cursorright-alignretrimrafripemd160run-asyncsafe-bufferrx-litesafe-regexsafer-buffersamsamset-blockingset-valueset-immediate-shimsetimmediatesha.jsshelljssigmundslashslice-ansisnapdragonsnapdragon-nodesnapdragon-utilsource-list-mapsource-mapsource-map-resolvesource-map-supportsource-map-urlspdx-correctspdx-exceptionsspdx-expression-parsesplit-stringspdx-license-idssprintf-jsstatic-extendstream-browserifystream-httpstring-widthstring_decoderstrip-ansistrip-bomstrip-json-commentssupports-colorsymbol-observabletabletapabletext-tablethroughtimers-browserifyto-arraybufferto-fast-propertiesto-iso-stringto-object-pathto-regexto-regex-rangetryittty-browserifytype-checktype-detecttypedarrayuglify-jsuglify-to-browserifyunion-valueupathunset-valueurixurluseuser-homeutilutil-deprecatev8flagsvm-browserifyvalidate-npm-package-licensewatchpack-chokidar2watchpackwebpack-sourceswhich-modulewindow-sizewordwrapwrap-ansiwrappywritextendy18nyargsyargs-parser
1.0.0

3 years ago