Skip to content

Instantly share code, notes, and snippets.

@balascript
Last active July 12, 2020 20:02
Show Gist options
  • Save balascript/ca12b0719a1c22cdeb6e5f1d7070d21b to your computer and use it in GitHub Desktop.
Save balascript/ca12b0719a1c22cdeb6e5f1d7070d21b to your computer and use it in GitHub Desktop.
custom hook to provide photos and fetchMore method to be used as a cursor to Flatlist
function useUnsplashPhotos(keyword) {
const [page, setPage] = useState(1);
// default this to true to kick the initial effect hook to
// fetch the first page
const [shouldFetch, setShouldFetch] = useState(true);
const [photos, setPhotos] = useState([]);
// return this function for Flatlist to call onEndReached
const fetchMore = useCallback(() => setShouldFetch(true), []);
useEffect(
() => {
// prevent fetching for other state changes
if (!shouldFetch) {
return;
}
const fetch = async () => {
const newPhotos = await fetchPhotos(keyword, page, 20);
// set the should fetch call to false to prevent fetching
// on page number update
setShouldFetch(false);
setPhotos(oldPhotos => [...oldPhotos, ...newPhotos]);
//increment page for the next call
setPage(page + 1);
};
fetch();
},
// prevent fetching for other state changes
[page, shouldFetch],
);
return [photos, fetchMore];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment