diff --git a/app/components/PaginatedList.tsx b/app/components/PaginatedList.tsx index ea7b9f86eb..b7644af5b3 100644 --- a/app/components/PaginatedList.tsx +++ b/app/components/PaginatedList.tsx @@ -1,15 +1,13 @@ import isEqual from "lodash/isEqual"; -import { observable, action, computed } from "mobx"; import { observer } from "mobx-react"; import * as React from "react"; -import { withTranslation, WithTranslation } from "react-i18next"; +import { useTranslation } from "react-i18next"; import { Waypoint } from "react-waypoint"; import { Pagination } from "@shared/constants"; -import RootStore from "~/stores/RootStore"; +import { useStores } from "~/hooks/useStores"; import ArrowKeyNavigation from "~/components/ArrowKeyNavigation"; import DelayedMount from "~/components/DelayedMount"; import PlaceholderList from "~/components/List/Placeholder"; -import withStores from "~/components/withStores"; import { dateToHeading } from "~/utils/date"; export interface PaginatedItem { @@ -18,248 +16,243 @@ export interface PaginatedItem { createdAt?: string; } -type Props = WithTranslation & - RootStore & - React.HTMLAttributes & { - fetch?: ( - options: Record | undefined - ) => Promise | undefined; - options?: Record; - heading?: React.ReactNode; - empty?: React.ReactNode; - loading?: React.ReactElement; - items?: T[]; - className?: string; - renderItem: (item: T, index: number) => React.ReactNode; - renderError?: (options: { - error: Error; - retry: () => void; - }) => React.ReactNode; - renderHeading?: (name: React.ReactElement | string) => React.ReactNode; - onEscape?: (ev: React.KeyboardEvent) => void; - listRef?: React.RefObject; - }; +type Props = React.HTMLAttributes & { + fetch?: ( + options: Record | undefined + ) => Promise | undefined; + options?: Record; + heading?: React.ReactNode; + empty?: React.ReactNode; + loading?: React.ReactElement; + items?: T[]; + className?: string; + renderItem: (item: T, index: number) => React.ReactNode; + renderError?: (options: { + error: Error; + retry: () => void; + }) => React.ReactNode; + renderHeading?: (name: React.ReactElement | string) => React.ReactNode; + onEscape?: (ev: React.KeyboardEvent) => void; + listRef?: React.RefObject; +}; -@observer -class PaginatedList extends React.PureComponent< - Props -> { - @observable - error?: Error; - - @observable - isFetchingMore = false; - - @observable - isFetching = false; - - @observable - isFetchingInitial = !this.props.items?.length; - - @observable - fetchCounter = 0; - - @observable - renderCount = Pagination.defaultLimit; - - @observable - offset = 0; - - @observable - allowLoadMore = true; - - componentDidMount() { - void this.fetchResults(); - } - - componentDidUpdate(prevProps: Props) { - if ( - prevProps.fetch !== this.props.fetch || - !isEqual(prevProps.options, this.props.options) - ) { - this.reset(); - void this.fetchResults(); - } - } - - reset = () => { - this.offset = 0; - this.allowLoadMore = true; - this.renderCount = Pagination.defaultLimit; - this.isFetching = false; - this.isFetchingInitial = false; - this.isFetchingMore = false; - }; - - @action - fetchResults = async () => { - if (!this.props.fetch) { +function PaginatedList({ + fetch, + options, + heading, + empty = null, + loading, + items = [], + className, + renderItem, + renderError, + renderHeading, + onEscape, + listRef, + ...rest +}: Props) { + const { auth } = useStores(); + const { t } = useTranslation(); + + const [error, setError] = React.useState(); + const [isFetchingMore, setIsFetchingMore] = React.useState(false); + const [isFetching, setIsFetching] = React.useState(false); + const [isFetchingInitial, setIsFetchingInitial] = React.useState(!items?.length); + const [fetchCounter, setFetchCounter] = React.useState(0); + const [renderCount, setRenderCount] = React.useState(Pagination.defaultLimit); + const [offset, setOffset] = React.useState(0); + const [allowLoadMore, setAllowLoadMore] = React.useState(true); + + const reset = React.useCallback(() => { + setOffset(0); + setAllowLoadMore(true); + setRenderCount(Pagination.defaultLimit); + setIsFetching(false); + setIsFetchingInitial(false); + setIsFetchingMore(false); + }, []); + + const fetchResults = React.useCallback(async () => { + if (!fetch) { return; } - this.isFetching = true; - const counter = ++this.fetchCounter; - const limit = this.props.options?.limit ?? Pagination.defaultLimit; - this.error = undefined; - + + setIsFetching(true); + const counter = fetchCounter + 1; + setFetchCounter(counter); + const limit = options?.limit ?? Pagination.defaultLimit; + setError(undefined); + try { - const results = await this.props.fetch({ + const results = await fetch({ limit, - offset: this.offset, - ...this.props.options, + offset, + ...options, }); - - if (this.offset !== 0) { - this.renderCount += limit; + + if (offset !== 0) { + setRenderCount((prevCount) => prevCount + limit); } - + if (results && (results.length === 0 || results.length < limit)) { - this.allowLoadMore = false; + setAllowLoadMore(false); } else { - this.offset += limit; + setOffset((prevOffset) => prevOffset + limit); } - - this.isFetchingInitial = false; + + setIsFetchingInitial(false); } catch (err) { - this.error = err; + setError(err); } finally { // only the most recent fetch should end the loading state - if (counter >= this.fetchCounter) { - this.isFetching = false; - this.isFetchingMore = false; + if (counter >= fetchCounter) { + setIsFetching(false); + setIsFetchingMore(false); } } - }; - - @action - loadMoreResults = async () => { - // Don't paginate if there aren't more results or we’re currently fetching - if (!this.allowLoadMore || this.isFetching) { + }, [fetch, fetchCounter, offset, options]); + + const loadMoreResults = React.useCallback(async () => { + // Don't paginate if there aren't more results or we're currently fetching + if (!allowLoadMore || isFetching) { return; } + // If there are already cached results that we haven't yet rendered because // of lazy rendering then show another page. - const leftToRender = (this.props.items?.length ?? 0) - this.renderCount; - + const leftToRender = (items?.length ?? 0) - renderCount; + if (leftToRender > 0) { - this.renderCount += Pagination.defaultLimit; + setRenderCount((prevCount) => prevCount + Pagination.defaultLimit); } - + // If there are less than a pages results in the cache go ahead and fetch // another page from the server if (leftToRender <= Pagination.defaultLimit) { - this.isFetchingMore = true; - await this.fetchResults(); + setIsFetchingMore(true); + await fetchResults(); } - }; - - @computed - get itemsToRender() { - return this.props.items?.slice(0, this.renderCount) ?? []; - } - - render() { - const { - items = [], - heading, - auth, - empty = null, - renderHeading, - renderError, - onEscape, - } = this.props; - - const showLoading = - this.isFetching && - !this.isFetchingMore && - (!items?.length || (this.fetchCounter <= 1 && this.isFetchingInitial)); - - if (showLoading) { - return ( - this.props.loading || ( - -
- -
-
- ) - ); + }, [allowLoadMore, isFetching, items?.length, renderCount, fetchResults]); + + // Equivalent to componentDidMount + React.useEffect(() => { + void fetchResults(); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, []); + + // Equivalent to componentDidUpdate + React.useEffect(() => { + const prevFetch = React.useRef(fetch); + const prevOptions = React.useRef(options); + + if ( + prevFetch.current !== fetch || + !isEqual(prevOptions.current, options) + ) { + reset(); + void fetchResults(); } - - if (items?.length === 0) { - if (this.error && renderError) { - return renderError({ error: this.error, retry: this.fetchResults }); - } - - return empty; - } - + + prevFetch.current = fetch; + prevOptions.current = options; + }, [fetch, options, reset, fetchResults]); + + // Computed property equivalent + const itemsToRender = React.useMemo(() => { + return items?.slice(0, renderCount) ?? []; + }, [items, renderCount]); + + const showLoading = + isFetching && + !isFetchingMore && + (!items?.length || (fetchCounter <= 1 && isFetchingInitial)); + + if (showLoading) { return ( - <> - {heading} - - {() => { - let previousHeading = ""; - return this.itemsToRender.map((item, index) => { - const children = this.props.renderItem(item, index); - - // If there is no renderHeading method passed then no date - // headings are rendered - if (!renderHeading) { - return children; - } - - // Our models have standard date fields, updatedAt > createdAt. - // Get what a heading would look like for this item - const currentDate = - "updatedAt" in item && item.updatedAt - ? item.updatedAt - : "createdAt" in item && item.createdAt - ? item.createdAt - : previousHeading; - const currentHeading = dateToHeading( - currentDate, - this.props.t, - auth.user?.language - ); - - // If the heading is different to any previous heading then we - // should render it, otherwise the item can go under the previous - // heading - if ( - children && - (!previousHeading || currentHeading !== previousHeading) - ) { - previousHeading = currentHeading; - return ( - - {renderHeading(currentHeading)} - {children} - - ); - } - - return children; - }); - }} - - {this.allowLoadMore && ( -
- + loading || ( + +
+
- )} - +
+ ) ); } + + if (items?.length === 0) { + if (error && renderError) { + return renderError({ error, retry: fetchResults }); + } + + return empty; + } + + return ( + <> + {heading} + + {() => { + let previousHeading = ""; + return itemsToRender.map((item, index) => { + const children = renderItem(item, index); + + // If there is no renderHeading method passed then no date + // headings are rendered + if (!renderHeading) { + return children; + } + + // Our models have standard date fields, updatedAt > createdAt. + // Get what a heading would look like for this item + const currentDate = + "updatedAt" in item && item.updatedAt + ? item.updatedAt + : "createdAt" in item && item.createdAt + ? item.createdAt + : previousHeading; + const currentHeading = dateToHeading( + currentDate, + t, + auth.user?.language + ); + + // If the heading is different to any previous heading then we + // should render it, otherwise the item can go under the previous + // heading + if ( + children && + (!previousHeading || currentHeading !== previousHeading) + ) { + previousHeading = currentHeading; + return ( + + {renderHeading(currentHeading)} + {children} + + ); + } + + return children; + }); + }} + + {allowLoadMore && ( +
+ +
+ )} + + ); } -export const Component = PaginatedList; +export const Component = observer(PaginatedList); -export default withTranslation()(withStores(PaginatedList)); +export default observer(PaginatedList);