Skip to content

Instantly share code, notes, and snippets.

@macalinao
Created February 26, 2019 20:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save macalinao/1ec946e997417726735c4c79091ed1e1 to your computer and use it in GitHub Desktop.
Save macalinao/1ec946e997417726735c4c79091ed1e1 to your computer and use it in GitHub Desktop.
import * as R from "ramda";
import { useState } from "react";
/**
* Default to displaying only pageSize items, but allow loadMore.
* @param items Items to return
* @param getId The serialized ID of the item.
* @param pageSize Number of items to display per page.
* @returns [filteredItems, loadMore, hasMore]
*/
function useLoadMore<T>(
items: T[],
getId: ((item: T) => string),
pageSize: number = 5
): [T[], () => void, boolean] {
const maybeNextId = items[pageSize];
const [nextId, setNextId] = useState<string | null>(
maybeNextId ? getId(maybeNextId) : null
);
return [
R.takeWhile(item => getId(item) !== nextId, items),
() => {
if (nextId === null) {
return;
}
const nextIndex = items.findIndex(item => getId(item) === nextId);
const maybeNextPageId = items[nextIndex + pageSize];
setNextId(maybeNextPageId ? getId(maybeNextPageId) : null);
},
!!nextId
];
}
export default useLoadMore;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment