I’m getting a user from my API and store it in my state so I don’t have to fetch it again. Problem is that multiple components requests the user at the same time resulting in multiple concurrent fetch requests.
Is there a good pattern to avoid this?
This is my saga
function* watchUserRequests() {
yield takeEvery(actionTypes.USER_REQUESTED, userRequested);
}
function* userRequested(action) {
const {id} = action.payload;
let user = yield select(state => state.users.all[id]);
// cancel if user exists
if (user) return;
user = yield call(userApi.get, id);
yield put(userActions.userLoaded(id, banner));
}
Actions
export function userRequested(id) {
return {type: types.USER_REQUESTED, payload: {id}};
}
export function userLoaded(id, user) {
return {type: types.USER_LOADED, payload: {id, user}};
}
It think you are looking for something like
That you can use like this
This is how I solved this problem in another saga. The "type" here can be ignored
Code:
Most of this comes from here: https://marmelab.com/blog/2016/10/18/using-redux-saga-to-deduplicate-and-group-actions.html