Closed
Description
I have thousands of lines along the lines of:
const thing = (state = {}, action) => {
if (action.type === 'FETCH_THING') {
if (!action.status) {
return {
...state,
fetchThingStatus: 'pending',
fetchThingStatusAt: +new Date,
fetchThingStatusError: null,
};
}
if (action.status === 'success') {
return {
...state,
fetchThingStatus: action.status,
fetchThingStatusAt: +new Date,
fetchThingStatusError: null,
};
}
if (action.status === 'error') {
return {
...state,
fetchThingStatus: action.status,
fetchThingStatusAt: +new Date,
fetchThingStatusError: action.error.stack,
};
}
}
return state;
};
const fetchThing = () => (dispatch, getState) => {
const action = {
type: 'FETCH_THING',
};
dispatch(action);
fetchThing({
/// ...
})
.then(() => {
dispatch({
...action,
status: 'success',
});
})
.catch(error => {
dispatch({
...action,
error: error.message,
});
});
};
const shouldFetchThing = (state) => {
const { thing } = state;
return thing.fetchThingStatus !== 'pending' &&
(!thing.fetchThingStatusAt || +new Date - thing.fetchThingStatusAt > 10 * 60e3);
};
const thingMiddleware = ({ getState, dispatch }) => {
setInterval(() => {
if (shouldFetchThing(getState())) {
dispatch(fetchThing());
}
}, 1e3);
return next => action => next(action);
};
The above example is the simplest case. In other cases there are updates with more complicated optimistic concurrency.