Say I have the following epic:
const getPostsEpic = (action$, store) => {
return action$.ofType(actionTypes.REQUEST_POSTS)
.switchMap(action =>
ajax.getJSON(`api/posts?key=${action.key}`)
.map(response =>
receivePosts({type: RECEIVE_POSTS, posts: response})
).takeUntil(
action$.ofType(actionTypes.ABORT_GET_POSTS)
)
};
and say my reducer is something like
function reducer(
state = {
isFetching: false,
didInvalidate: true,
items: []
},
action
) {
switch (action.type) {
case INVALIDATE_POSTS:
return Object.assign({}, state, {
didInvalidate: true
})
case REQUEST_POSTS:
return Object.assign({}, state, {
isFetching: true,
didInvalidate: false
})
case RECEIVE_POSTS:
return Object.assign({}, state, {
isFetching: false,
didInvalidate: false,
items: action.posts,
})
default:
return state
}
}
I want to make sure that posts are only fetched if my state's didInvalidate === true
, is there a good way to make this work with my epic? Could do something like this, but it's not that pretty IMO:
const getPostsEpic = (action$, store) => {
return action$.ofType(actionTypes.REQUEST_POSTS)
.switchMap(action => {
const state = store.getState();
if (state.didInvalidate) {
return ajax.getJSON(`api/posts?key=${action.key}`)
.map(response =>
receivePosts({type: RECEIVE_POSTS, posts: response})
).takeUntil(
action$.ofType(actionTypes.ABORT_GET_POSTS)
)
else {
return Observable.of({type: RECEIVE_POSTS, posts: state.items});
}
}
};
Btw, I'm using this with React. I'm sure this is a pretty common problem, so maybe there's a better way of handling this outside my epics?