Answer the question
In order to leave comments, you need to log in
How to properly organize the phased loading of data from the server?
1 problem : how and where to network the data in the store? (I don’t really like that I divided the logic into state and store - maybe offset should be networked in the store?)
const enrollments = useSelector((state) => get(state, 'app.enrollments') || []);
const [filter, setFilter] = useState(get(FILTERS, '0.value'));
const [offset, setOffset] = useState(0);
const countEnrollments = useRef(enrollments.length);
const isButtonHidden =
enrollments.length === countEnrollments.current || enrollments.length % DEFAULT_COUNT_ITEMS_PER_PAGE !== 0;
const onLoadEnrollments = () => setOffset(offset + 1);
const loadEnrollments = () => dispatch(getEnrollments({ userId, filter, offset }));
const clearEnrollments = () => dispatch(setEnrollments([]));
useEffect(loadEnrollments, [filter, offset]);
useEffect(() => {
setOffset(0);
clearEnrollments();
set(countEnrollments, 'current', 0);
}, [filter]);
useEffect(() => {
const length = get(enrollments, 'length', 0);
const current = get(countEnrollments, 'current', 0);
if (length !== current) {
set(countEnrollments, 'current', length);
}
}, [enrollments]);
// getEnrollments
export const getEnrollments = (data) => async (dispatch, getState) => {
const [execute] = apiShell(callEnrollments, dispatch);
const response = await execute(data);
const enrollments = get(response, 'enrollments') || [];
const offset = get(data, 'offset');
if (!offset) {
dispatch(setEnrollments(enrollments));
return;
}
const store = getState();
const storeEnrollments = get(store, 'app.enrollments') || [];
dispatch(setEnrollments([...storeEnrollments, ...enrollments]));
};
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question