Skip to content

Commit

Permalink
#75 fixed problem with cancel request in debounce function.
Browse files Browse the repository at this point in the history
  • Loading branch information
artzub committed Jan 8, 2021
1 parent 2d364ee commit 729089e
Show file tree
Hide file tree
Showing 4 changed files with 13 additions and 16 deletions.
6 changes: 2 additions & 4 deletions src/components/Header/components/ProfileStep/Body.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -95,13 +95,11 @@ const Body = () => {

useDebounce(
() => {
dispatch(slice.actions.cancel());

if (search) {
dispatch(slice.actions.search(search));
}

return () => {
dispatch(slice.actions.cancel());
};
},
300,
[search, dispatch],
Expand Down
1 change: 1 addition & 0 deletions src/redux/modules/profiles.js
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ export default createSlice({
yield put(actions.fail(error));
} finally {
if (yield cancelled()) {
console.log('cancelled');
yield put(actions.stopFetching());
}
}
Expand Down
10 changes: 6 additions & 4 deletions src/redux/modules/progress.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,11 @@ export default createSlice({
};

if (show) {
startFetching(newState, { payload: 'show' });
startFetching(newState);
} else if (show === false) {
stopFetching(newState, { payload: 'show' });
stopFetching(newState);
}
state.show = state.isFetching;

return newState;
},
Expand All @@ -40,10 +41,11 @@ export default createSlice({
toggle: (state, { payload }) => {
const show = payload ?? !state.show;
if (show) {
startFetching(state, { payload: 'show' });
startFetching(state);
} else {
stopFetching(state, { payload: 'show' });
stopFetching(state);
}
state.show = state.isFetching;
},
},
});
12 changes: 4 additions & 8 deletions src/redux/utils/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,24 +5,20 @@ export * from './withCancellation';
/**
* incs counter of request and set isFetching to true
* @param state
* @param {String} payload - name of property
*/
export const startFetching = (state, { payload } = {}) => {
const prop = typeof payload === 'string' ? payload : 'isFetching';
state[prop] = true;
export const startFetching = (state) => {
state.isFetching = true;
state._requests = (state._requests ?? 0) + 1;
state.error = '';
};

/**
* decs counter of request and set isFetching to false if counter less than 1.
* @param state
* @param {String} [payload] - name of property
*/
export const stopFetching = (state, { payload } = {}) => {
const prop = typeof payload === 'string' ? payload : 'isFetching';
export const stopFetching = (state) => {
state._requests = Math.max(0, (state._requests ?? 1) - 1);
state[prop] = !!state._requests;
state.isFetching = !!state._requests;
};

/**
Expand Down

0 comments on commit 729089e

Please sign in to comment.