Skip to content

Instantly share code, notes, and snippets.

@stevenjohn
Created December 29, 2019 02:51
Show Gist options
  • Save stevenjohn/cefc8f23570e70bad8a82d10982975f4 to your computer and use it in GitHub Desktop.
Save stevenjohn/cefc8f23570e70bad8a82d10982975f4 to your computer and use it in GitHub Desktop.
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