Proyectos de Subversion LeadersLinked - SPA

Rev

Rev 3481 | Rev 3511 | Ir a la última revisión | Autoría | Comparar con el anterior | Ultima modificación | Ver Log |

import React, { useCallback, useEffect, useRef, useState } from 'react';

import { useSelector } from 'react-redux';
import { Box, Typography } from '@mui/material';

import { useNearScreen, useMicroLearning } from '@hooks';
import { api } from '@shared/libs';
import { List, Spinner } from '@shared/components';
import DetailTag from '@microlearning/components/DetailTag';

export function TimelinePage() {
  const { link_timeline: linkTimeline } = useMicroLearning();
  const [items, setItems] = useState([]);
  const [isLoading, setIsLoading] = useState(false);
  const [totalPages, setTotalPages] = useState(1);
  const [currentPage, setCurrentPage] = useState(2);
  const loaderRef = useRef(null);
  const [isIntercepting] = useNearScreen({
    externalRef: loaderRef,
    once: false,
    rootMargin: '20px'
  });

  const fetchData = useCallback(
    (url = '') => {
      if (isLoading || !url) return;

      setIsLoading(true);

      api
        .get(`${url}?page=${currentPage}`)
        .then((data) => {
          setCurrentPage((prevCurrentPage) => prevCurrentPage + 1);
          setTotalPages(data.total.pages);
          setItems((prevItems) => [...prevItems, ...data.current.items]);
        })
        .catch((err) => console.log(err.message))
        .finally(() => setIsLoading(false));
    },
    [currentPage, isLoading, totalPages, linkTimeline]
  );

  useEffect(() => {
    if (isIntercepting) fetchData(linkTimeline);
  }, [isIntercepting]);

  useEffect(() => {
    const getData = (url = '') => {
      setIsLoading(true);

      api
        .get(url)
        .then((response) => {
          const { data, success } = response.data;

          if (!success) {
            throw new Error(data);
          }

          setTotalPages(data.total.pages);
          setItems(data.current.items);
        })
        .catch((err) => console.log(err.message))
        .finally(() => setIsLoading(false));
    };

    getData(linkTimeline);
  }, [linkTimeline]);

  return (
    <>
      <Typography variant='h2'>Linea de tiempo</Typography>

      <Box
        display='flex'
        flexDirection='column'
        gap={1}
        width='100%'
        mt={2}
        maxHeight='60vh'
        overflow='auto'
      >
        <TimelineList items={items} />

        <div ref={loaderRef}>{currentPage < totalPages ? <Spinner /> : null}</div>
      </Box>
    </>
  );
}

const TimelineList = ({ items = [] }) => {
  const labels = useSelector(({ intl }) => intl.labels);

  return (
    <List
      items={items}
      emptyMessage={labels.datatable_szerorecords}
      renderItem={({ activity, added_on }, i) => (
        <DetailTag key={i} title={activity} label={added_on} />
      )}
    />
  );
};