Last active
August 19, 2019 12:42
-
-
Save Ackuq/7b63b34aff5816d6c0e07c3e2dd132a0 to your computer and use it in GitHub Desktop.
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
import React, { useEffect, useState } from 'react'; | |
import { FlatList, SafeAreaView, Text } from 'react-native'; | |
import PropTypes from 'prop-types'; | |
import { fetchApiData } from '../../lib/api'; | |
const Posts = ({ navigation }) => { | |
const [posts, setPosts] = useState([]); | |
const [page, setPage] = useState(1); | |
const [loading, setLoading] = useState(true); | |
const [lastPage, setLastPage] = useState(false); | |
useEffect(() => { | |
const route = `posts?per_page=10&page=${page}`; | |
fetchApiData(route).then(res => { | |
if (res.code !== 'rest_post_invalid_page_number') { | |
setPosts(prevPosts => [...prevPosts, ...res]); | |
} else { | |
setLastPage(true); | |
} | |
setLoading(false); | |
}); | |
}, [page]); | |
return ( | |
<SafeAreaView style={{ flex: 1, paddingTop: 5 }}> | |
{posts.length > 0 ? ( | |
<FlatList | |
onEndReached={() => { | |
if (!loading && !lastPage) { | |
setPage(prevPage => prevPage + 1); | |
} | |
}} | |
keyExtractor={item => item.id.toString()} | |
data={posts} | |
renderItem={({ item }) => ( | |
<TouchableOpacity onPress={() => navigation.navigate('Post', { id: item.id })}> | |
<View> | |
<Text>{item.title.rendered}</Text> | |
<Text>{item.excerpt.rendered}</Text> | |
</View> | |
</TouchableOpacity> | |
) | |
} | |
/> | |
) : ( | |
<Text>Loading...</Text> | |
)} | |
</SafeAreaView> | |
); | |
}; | |
Posts.propTypes = { | |
navigation: PropTypes.object.isRequired, | |
}; | |
export default Posts; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment