When writing redux-thunk functions known as thunks, there is a dedicated template that can be easily distracted. For example, in most of our asynchronous API calls, we do the following without any 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, since this covers at least 70% of our queries, I am sure there is an elegant way to ignore the allocation of the above code to something like this (pseudocode):
export function login(loginHandle, password) { return (dispatch, getState, api) => api('POST', LOGIN_REQUEST, '/auth/login', { loginHandle, password }); }
When we need to check the condition and other side effects, we can return to the correct tick. Although in most cases ... could we cut it?
Any elegant ideas?
javascript reactjs redux redux-thunk redux-saga
AndrewMcLagan
source share