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

Redux middleware for fetching data with axios HTTP client

License

NotificationsYou must be signed in to change notification settings

svrcekmichal/redux-axios-middleware

Repository files navigation

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 namespaceReduxAxiosMiddleware

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';importaxiosfrom'axios';importaxiosMiddlewarefrom'redux-axios-middleware';constclient=axios.create({//all axios can be used, shown in axios documentationbaseURL:'http://localhost:8080/api',responseType:'json'});letstore=createStore(reducers,//custom reducersapplyMiddleware(//all middlewares    ...axiosMiddleware(client),//second parameter options can optionally contain onSuccess, onError, onComplete, successSuffix, errorSuffix    ...))

Dispatch action

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

  • useaction.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"

exportfunctionloadCategories(){return{type:'LOAD',payload:{request:{url:'/categories'}}}}
  • useaction.types with array of types[REQUEST,SUCCESS,FAILURE]
  • REQUEST will be dispatched on start, thenSUCCESS orFAILURE after request result
exportfunctionloadCategories(){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 awaythis.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 typepayload:{ ...}//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 keypayload, but now there'serror;

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

if axios failed fatally, default error action with status0 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:

exportfunctionloadCategories(){return{type:'LOAD',payload:{client:'default',//here you can define client usedrequest:{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 configC - client configA - action config

keytypedefault valuechange leveldescription
successSuffixstringSUCCESSMCAdefault suffix added to success action, for example{type:"READ"} will be{type:"READ_SUCCESS"}
errorSuffixstringFAILMCAsame as above
onSuccessfunctiondescribed aboveMCAfunction called if axios resolve with success
onErrorfunctiondescribed aboveMCAfunction called if axios resolve with error
onCompletefunctiondescribed aboveMCAfunction called after axios resolve
returnRejectedPromiseOnErrorboolfalseMCAiftrue, axios onError handler will returnPromise.reject(newAction) instead ofnewAction
isAxiosRequestfunctionfunction check if action containaction.payload.requestMcheck if action is axios request, this is connected togetRequestConfig
getRequestConfigfunctionreturn content ofaction.payload.requestMCAifisAxiosRequest returns true, this function get axios request config from action
getClientNamefunctionreturnsaction.payload.client OR'default'MCAattempts to resolve used client name or use defaultClientName
defaultClientNameevery possible object key type'default'Mkey which define client used ifgetClienName returned false value
getRequestOptionsfunctionreturnaction.payload.optionsMCreturns options object from action to override some values
interceptorsobject{request: [], response: []}MCYou can pass axios request and response interceptors. Take care, first argument of interceptor is different from default axios interceptor, first received argument is object withgetState,dispatch andgetAction keys

interceptors

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

constmiddlewareConfig={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 torequest and\orresponse arrays with correspondingsuccess and\orerror functions.

Example:

constmiddlewareConfig={interceptors:{request:[{success:function({getState, dispatch, getSourceAction},req){console.log(req);//contains information about request object//...returnreq;},error:function({getState, dispatch, getSourceAction},error){//...returnresponse}}],response:[{success:function({getState, dispatch, getSourceAction},res){console.log(res);//contains information about request object//...returnPromise.resolve(res);},error:function({getState, dispatch, getSourceAction},error){returnPromise.reject(error);}}]}};

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

letstore=createStore(reducers,//custom reducersapplyMiddleware(//all middlewares    ...axiosMiddleware(client,middlewareConfig),    ...))

Examples

License

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

Acknowledgements

Dan Abramov for ReduxMatt Zabriskie forAxios. A Promise based HTTP client for the browser and node.js

About

Redux middleware for fetching data with axios HTTP client

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Contributors16


[8]ページ先頭

©2009-2025 Movatter.jp