|
| 1 | +import PropTypes from 'prop-types'; |
| 2 | +import React, { useEffect, useMemo } from 'react'; |
| 3 | +import BeatLoader from 'react-spinners/BeatLoader'; |
| 4 | + |
| 5 | +import { ITEMS_PER_PAGE } from 'constants/numbers'; |
| 6 | + |
| 7 | +import Story from 'components/Pages/PageView/Components/Story'; |
| 8 | +import NextPage from 'components/Pages/PageView/Components/NextPage'; |
| 9 | + |
| 10 | +/** |
| 11 | + * Page View Component. |
| 12 | + * |
| 13 | + * @param {*} props |
| 14 | + * |
| 15 | + * @returns {Component} |
| 16 | + */ |
| 17 | +function PageView({ |
| 18 | + news = [], |
| 19 | + match = {}, |
| 20 | + gettingAllNewsError, |
| 21 | + gettingAllNews = false, |
| 22 | + gettingAllNewsSuccess = false, |
| 23 | + |
| 24 | + getAllNews = () => {} |
| 25 | +}) { |
| 26 | + const { newsType = 'top', page = 1 } = match?.params; |
| 27 | + const currentPageNumber = parseInt(page); |
| 28 | + |
| 29 | + useEffect(() => { |
| 30 | + const newsEndpoint = newsType + 'stories.json'; |
| 31 | + |
| 32 | + getAllNews({ |
| 33 | + newsType: newsEndpoint |
| 34 | + }); |
| 35 | + }, [newsType, getAllNews]); |
| 36 | + |
| 37 | + const stories = useMemo(() => { |
| 38 | + const previousPage = currentPageNumber - 1; |
| 39 | + const startItemsIndex = previousPage * ITEMS_PER_PAGE; |
| 40 | + const endItemsIndex = currentPageNumber * ITEMS_PER_PAGE; |
| 41 | + |
| 42 | + const currentPageStories = news?.slice(startItemsIndex, endItemsIndex) || []; |
| 43 | + |
| 44 | + return currentPageStories; |
| 45 | + }, [news, currentPageNumber]); |
| 46 | + |
| 47 | + if (gettingAllNews) { |
| 48 | + return ( |
| 49 | + <div className="center mt-20 mb-20"> |
| 50 | + <BeatLoader color="#F46526" loading={gettingAllNews} size={20} margin={5} /> |
| 51 | + </div> |
| 52 | + ); |
| 53 | + } else if (!gettingAllNews && !gettingAllNewsSuccess && gettingAllNewsError) { |
| 54 | + return ( |
| 55 | + <div className="center"> |
| 56 | + <p className="text-danger">{gettingAllNewsError}</p> |
| 57 | + </div> |
| 58 | + ); |
| 59 | + } |
| 60 | + |
| 61 | + return ( |
| 62 | + <div> |
| 63 | + {stories.map((storyId, index) => ( |
| 64 | + <Story key={storyId} storyId={storyId} storyIndex={(currentPageNumber - 1) * ITEMS_PER_PAGE + index + 1} /> |
| 65 | + ))} |
| 66 | + |
| 67 | + <NextPage newsType={newsType} page={page} news={news} /> |
| 68 | + </div> |
| 69 | + ); |
| 70 | +} |
| 71 | + |
| 72 | +PageView.propTypes = { |
| 73 | + getAllNews: PropTypes.func, |
| 74 | + gettingAllNews: PropTypes.bool, |
| 75 | + gettingAllNewsError: PropTypes.any, |
| 76 | + gettingAllNewsSuccess: PropTypes.bool, |
| 77 | + match: PropTypes.object, |
| 78 | + news: PropTypes.array |
| 79 | +}; |
| 80 | + |
| 81 | +export default PageView; |
0 commit comments