Skip to content

Instantly share code, notes, and snippets.

@diegomais
Created January 8, 2021 17:02
Show Gist options
  • Save diegomais/c03062fb9122c0369ef2bd6cba5a47d0 to your computer and use it in GitHub Desktop.
Save diegomais/c03062fb9122c0369ef2bd6cba5a47d0 to your computer and use it in GitHub Desktop.
Infinite scroll/Paginating Flatlist by @srbkrishnan
import Unsplash, { toJson } from 'unsplash-js';
const unsplashInstance = new Unsplash({
secret: 'Your secret here',
accessKey: 'Your accessKey here',
});
async function fetchPhotos(keyword, page, limit = 10) {
const photoResult = await unsplashInstance.search
.photos(keyword, page, limit)
.then(toJson);
if (!Array.isArray(photoResult.results)) {
return [];
}
// map the response to a simpler format for Flatlist
const photos = photoResult.results.map(({ urls, id }) => ({
key: id,
uri: urls.small,
}));
return photos;
}
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];
}
const UnsplashFeed = props => {
const [photos, fetchMore] = useUnsplashPhotos('dogs');
const renderItem = ({ item, index }) => {
const { uri } = item;
return (
<Image
source={{ uri }}
style={{ height: 400 }}
resizeMode="cover"
/>
);
};
return (
<View style={{ flex: 1 }}>
<FlatList
data={photos}
renderItem={renderItem}
onEndReachedThreshold={0.9}
onEndReached={fetchMore}
/>
</View>
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment