Created
February 24, 2022 10:30
-
-
Save biomathcode/f94a2f19c529ec114a6aee5f2a410ff1 to your computer and use it in GitHub Desktop.
infinite scroll with recoil example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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