Created
December 29, 2019 02:51
-
-
Save stevenjohn/cefc8f23570e70bad8a82d10982975f4 to your computer and use it in GitHub Desktop.
WP post display using https://medium.com/swlh/creating-a-react-native-app-with-wordpress-backend-b56f8dc1d21c
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'; | |
export const fetchApiData = async route => { | |
try { | |
const response = await fetch("https://impact.task.io/wp-json/v2/" + route); | |
const json = await response.json(); | |
return json; | |
//console.log("JSON " + JSON.stringify(json, null, 2)); | |
} catch (error) { | |
console.error(error); | |
return null; | |
} | |
}; | |
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