Created
January 8, 2021 18:26
-
-
Save diegomais/a6c13524e3227c8723fe69afd591244c to your computer and use it in GitHub Desktop.
Infinite scroll/Paginating Flatlist by @diegomais
This file contains hidden or 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
import Unsplash, { toJson } from 'unsplash-js' | |
const unsplashInstance = new Unsplash({ | |
secret: 'Your secret here', | |
accessKey: 'Your accessKey here', | |
}) | |
const UnsplashFeed = () => { | |
const [error, setError] = useState() | |
const [isFetching, setIsFetching] = useState(true) | |
const [isRefreshing, setIsRefreshing] = useState(false) | |
const [items, setItems] = useState([]) | |
const [keyword, setKeyword] = useState('dog') | |
const [page, setPage] = useState(1) | |
const pagination = 1 | |
const fetchItems = useCallback(async () => { | |
try { | |
const response = await unsplashInstance.search | |
.photos(keyword, page, pagination) | |
.then(toJson) | |
if (!Array.isArray(response.results)) { | |
return | |
} | |
// map the response to a simpler format for Flatlist | |
const photos = response.results.map(({ urls, id }) => ({ | |
key: id, | |
uri: urls.small, | |
})) | |
setItems(prevItems => page === 1 ? photos : [...prevItems, ...photos]) | |
} catch (error) { | |
setError(error) | |
setIsFetching(false) | |
} | |
}, [keyword, page]) | |
const handleEndReached = useCallback(() => { | |
setPage(prevPage => prevPage + pagination) | |
}, []) | |
const handleRefresh = useCallback(() => { | |
setIsRefreshing(true) | |
if (page !== 0) { | |
setPage(0) | |
} else { | |
fetchItems() | |
} | |
wait(1000).then(() => setIsRefreshing(false)) | |
}, [fetchItems, page]) | |
const renderItem = ({ item }) => ( | |
<Image | |
resizeMode="cover" | |
source={{ uri: item.uri }} | |
style={{ height: 400 }} | |
/> | |
) | |
useEffect(() => { | |
fetchItems() | |
}, [fetchItems]) | |
return ( | |
<View style={{ flex: 1 }}> | |
<FlatList | |
data={items} | |
renderItem={renderItem} | |
onEndReachedThreshold={0.9} | |
onEndReached={handleEndReached} | |
refreshControl={ | |
<RefreshControl onRefresh={handleRefresh} refreshing={isRefreshing} /> | |
} | |
/> | |
</View> | |
) | |
} | |
export default UnsplashFeed |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment