L
L
lexstile2021-10-26 13:55:14
React
lexstile, 2021-10-26 13:55:14

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?)

spoiler
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]));
};

Problem 2 : displaying the button (isButtonHidden)
I have so far attached to the remainder of the division - if < 10 elements arrived, then they all arrived,
and if the next request returned the same number of elements as the previous one, then the next request will no longer return and we can don't show the button.
The problem is that if 10 elements have arrived, then we don’t know if they are the last ones or not, the button is shown and we need to click on it at least once (the only solution that came to mind is returning the total number of elements with BE ).

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question