javascript - Reducing redux-thunk boilerplate -


when writing redux-thunk functions, known thunks there allot of boilerplate abstracted away. example in of our async api calls doing following, without side-effects:

export const login_request = 'my-app/auth/login_request'; export const login_recieve = 'my-app/auth/login_recieve'; export const login_failure = 'my-app/auth/login_failure';  // ... reducer code here  export function login(loginhandle, password) {   return (dispatch, getstate, api) => {     dispatch({ type: login_request });      api.post('/auth/login', { loginhandle, password }).then(       response => dispatch({ type: login_recieve, response }),       error => dispatch({ type: login_failure, error })     );   }; } 

easy! although covers @ least 70% of our requests i'm sure there elegant way abstract away allot of above code (pseudo code):

export function login(loginhandle, password) {   return (dispatch, getstate, api) => api('post', login_request, '/auth/login', { loginhandle, password }); } 

when need check state , other side effects can go proper thunk. although cases... cut down?

any elegant ideas?

redux thunk lets inject custom argument since 2.1.0.

const api = createapi() // write function const store = createstore(   reducer,   applymiddleware(thunk.withextraargument(api)) )  // action creator: function fetchuser(id) {   return (dispatch, getstate, api) => {     // can use api here   } } 

in future, if thunks complicated, might want consider redux-saga or redux-observable.


Comments

Popular posts from this blog

scala - 'wrong top statement declaration' when using slick in IntelliJ -

c# - DevExpress.Wpf.Grid.InfiniteGridSizeException was unhandled -

PySide and Qt Properties: Connecting signals from Python to QML -