agraboso / agraboso/redux-api-middleware

Bailout during REQUEST

Abierto
#94 3 comentarios 0 reacciones 0 asignados Ver en GitHub
enhancement question
Lenguaje dominante
JavaScript
Estrellas
1.5k
Forks
190
Métricas de merge de PR
Sin PR fusionados en 30 d

Descripción

My application consist of multiple components that do a request when they are constructed. The problem is a request should only be done once because otherwise there are multiple requests to the same endpoint. Initially I attempted to get the required state in the bailout method and check if the store was `inProgress`. After some attempts I however found out that bailout is only checked upon initialization and not checked again pre-action.

Setting `inProgress: true` on my REQUEST (`GIFTS_LOAD`) does not work like I expect it to work. Below you can check out my temporary solution to prevent duplicate request from being executed. The reason is that the components listen to the state anyway, thus only a single set of actions should be executed.

_The concept behind this is based on the following:_
http://www.zohaib.me/redux-call-service-async/
http://redux.js.org/docs/advanced/AsyncActions.html (search for `shouldFetchPosts`)

How can I solve this in a cleaner way or is this how it's supposed to work?

**Action**

``` js
export function getGifts(accountId) {
return function(dispatch) {
dispatch({
[CALL_API]: {
endpoint: `${baseConfig.apiBaseUrl}${accountId}/gifts/`,
method: 'GET',
types: [types.GIFTS_LOAD, types.GIFTS_LOAD_SUCCESS, types.GIFTS_LOAD_FAILURE],
bailout: (state) => {
if (!(state.gift.fetched || state.gift.inProgress)) {
dispatch({ type: types.GIFTS_PENDING });
}

//Cancel request if already in progress
return !!(state.gift.fetched || state.gift.inProgress);
},
headers,
credentials: 'same-origin'
}
});
};
}
```

**Reducer**

``` js
export default function gift (state = initialState, action) {
switch (action.type) {
case types.GIFTS_PENDING:
return {
...state,
inProgress: true
};
case types.GIFTS_LOAD_SUCCESS:
return {
...state,
gifts: action.payload,
fetched: true,
inProgress: false,
error: false
};
case types.GIFTS_LOAD_FAILURE:
return {
...state,
inProgress: false,
error: true
};
case types.CLAIM_GIFT_SUCCESS:
return {
...state,
gifts: mutate(state, action)
};
default:
return state;
}
};
```

Guía de contribución

Abrir la guía de contribución

Evaluación

Este issue todavía no se ha evaluado.

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.