| 6 | import PhotoGrid from './components/PhotoGrid' |
| 7 | |
| 8 | export default function App() { |
| 9 | const [state, dispatch] = useReducer(reducer, initialState) |
| 10 | |
| 11 | const { photos, nextPage, loading, error } = state |
| 12 | |
| 13 | const fetchPhotos = useCallback(async () => { |
| 14 | dispatch(actionCreators.loading()) |
| 15 | |
| 16 | try { |
| 17 | const nextPhotos = await getList(nextPage) |
| 18 | dispatch(actionCreators.success(nextPhotos, nextPage)) |
| 19 | } catch (e) { |
| 20 | dispatch(actionCreators.failure()) |
| 21 | } |
| 22 | }, [nextPage]) |
| 23 | |
| 24 | useEffect(() => { |
| 25 | fetchPhotos() |
| 26 | }, []) |
| 27 | |
| 28 | // We'll show an error only if the first page fails to load |
| 29 | if (photos.length === 0) { |
| 30 | if (loading) { |
| 31 | return ( |
| 32 | <View style={styles.container}> |
| 33 | <ActivityIndicator animating={true} /> |
| 34 | </View> |
| 35 | ) |
| 36 | } |
| 37 | |
| 38 | if (error) { |
| 39 | return ( |
| 40 | <View style={styles.container}> |
| 41 | <Text>Failed to load photos!</Text> |
| 42 | </View> |
| 43 | ) |
| 44 | } |
| 45 | } |
| 46 | |
| 47 | return <PhotoGrid numColumns={3} photos={photos} onEndReached={fetchPhotos} /> |
| 48 | } |
| 49 | |
| 50 | const styles = StyleSheet.create({ |