Skip to content

Instantly share code, notes, and snippets.

@biomathcode
Created February 24, 2022 10:30
Show Gist options
  • Save biomathcode/f94a2f19c529ec114a6aee5f2a410ff1 to your computer and use it in GitHub Desktop.
Save biomathcode/f94a2f19c529ec114a6aee5f2a410ff1 to your computer and use it in GitHub Desktop.
infinite scroll with recoil example
const itemQuery = selectorFamily({
key: 'ItemQuery',
get: cursor => () => ApiCall(cursor),
});
const currentCursorInternal = atom<number>({
key: 'currentCursorInternal',
default: 0,
});
export function useFetchMoreItems() {
const setCurrentCursor = useSetRecoilState(currentCursorInternal);
return () => setCurrentCursor(cursor => cursor + 1);
}
export const allItems = selector({
key: 'AllItems',
get: ({get}) => {
const current = get(currentCursorInternal);
const cursorRange = Array.from(Array(current).keys());
return get(waitForNone(cursorRange.map(itemQuery)));
},
});
function ShowItemsComponent() {
const itemLoadables = useGetRecoilValue(allItems);
const fetchMoreItems = useFetchMoreItems();
return (
<div>
<button onClick={fetchMoreItems}>Fetch More Items</button>
{itemLoadables.map(itemLoadable => ({
hasValue: <Item item={itemLoadable.contents} key={itemLoadable.contents} />,
hasError: <Error error={itemLoadable.contents} key={itemLoadable.contents} />,
loading: <CoolShimmer key={itemLoadable.contents} />,
}[itemLoadable.state])}
</div>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment