Lesson 8 of 9
Mini Project: News Feed with TanStack Query + Offline
Build a complete news feed: infinite scroll via useInfiniteQuery, pull-to-refresh, optimistic like toggle, offline banner via NetInfo, and image prefetching. This is the complete production pattern for any social or content feed.
Complete News Feed Implementation
import { useInfiniteQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { FlatList, View, Text, Pressable, ActivityIndicator, StyleSheet } from 'react-native';
import { Image } from 'expo-image';
import { SafeAreaView } from 'react-native-safe-area-context';
interface Article {
id: string;
title: string;
excerpt: string;
imageUri: string;
author: string;
publishedAt: string;
liked: boolean;
likeCount: number;
}
// ---- Article Card ----
const ArticleCard = React.memo(({ article, onLike }: { article: Article; onLike: (id: string) => void }) => (
<Pressable style={s.card} accessibilityRole="button" accessibilityLabel={`Read ${article.title}`}>
<Image source={{ uri: article.imageUri }} style={s.image} contentFit="cover" cachePolicy="memory-disk" recyclingKey={article.id} />
<View style={s.cardBody}>
<Text style={s.cardTitle} numberOfLines={2}>{article.title}</Text>
<Text style={s.cardExcerpt} numberOfLines={2}>{article.excerpt}</Text>
<View style={s.cardFooter}>
<Text style={s.author}>{article.author}</Text>
<Pressable
onPress={() => onLike(article.id)}
style={s.likeBtn}
accessibilityRole="button"
accessibilityLabel={article.liked ? 'Unlike article' : 'Like article'}
accessibilityState={{ checked: article.liked }}
>
<Text style={{ fontSize: 16 }}>{article.liked ? 'โค๏ธ' : '๐ค'}</Text>
<Text style={s.likeCount}>{article.likeCount}</Text>
</Pressable>
</View>
</View>
</Pressable>
));
// ---- Screen ----
export default function NewsFeed() {
const queryClient = useQueryClient();
const { isConnected } = useNetworkStatus();
const {
data, isLoading, isError, fetchNextPage,
hasNextPage, isFetchingNextPage, refetch, isRefetching,
} = useInfiniteQuery({
queryKey: ['articles'],
queryFn: async ({ pageParam = 1 }) => {
const res = await apiClient.get('/articles', { params: { page: pageParam, limit: 10 } });
return res.data as { articles: Article[]; hasNextPage: boolean; page: number };
},
getNextPageParam: (last) => last.hasNextPage ? last.page + 1 : undefined,
initialPageParam: 1,
staleTime: 60_000,
});
const likeMutation = useMutation({
mutationFn: (articleId: string) => apiClient.post(`/articles/${articleId}/like`),
onMutate: async (articleId) => {
await queryClient.cancelQueries({ queryKey: ['articles'] });
const previous = queryClient.getQueryData(['articles']);
// Optimistic update
queryClient.setQueryData(['articles'], (old: unknown) => {
const data = old as { pages: { articles: Article[] }[] };
return {
...data,
pages: data.pages.map(page => ({
...page,
articles: page.articles.map(a =>
a.id === articleId
? { ...a, liked: !a.liked, likeCount: a.liked ? a.likeCount - 1 : a.likeCount + 1 }
: a
),
})),
};
});
return { previous };
},
onError: (_, __, ctx) => queryClient.setQueryData(['articles'], ctx?.previous),
onSettled: () => queryClient.invalidateQueries({ queryKey: ['articles'] }),
});
const articles = data?.pages.flatMap(p => p.articles) ?? [];
const renderItem = useCallback(({ item }: { item: Article }) => (
<ArticleCard article={item} onLike={id => likeMutation.mutate(id)} />
), [likeMutation]);
if (isLoading) return <View style={s.centered}><ActivityIndicator size="large" color="#229c6b" /></View>;
if (isError) return <View style={s.centered}><Text style={{ color: '#f87171' }}>Failed to load articles</Text></View>;
return (
<SafeAreaView style={s.screen} edges={['top']}>
{!isConnected && (
<View style={s.offlineBanner}>
<Text style={s.offlineText}>โก Offline - showing cached content</Text>
</View>
)}
<FlatList
data={articles}
keyExtractor={a => a.id}
renderItem={renderItem}
onEndReached={() => { if (hasNextPage && !isFetchingNextPage) fetchNextPage(); }}
onEndReachedThreshold={0.4}
ListHeaderComponent={<Text style={s.heading}>Top Stories</Text>}
ListFooterComponent={isFetchingNextPage ? <ActivityIndicator style={{ margin: 20 }} /> : null}
refreshing={isRefetching}
onRefresh={refetch}
contentContainerStyle={{ padding: 16, gap: 16, paddingBottom: 40 }}
showsVerticalScrollIndicator={false}
/>
</SafeAreaView>
);
}
function useNetworkStatus() {
const [isConnected, setIsConnected] = React.useState(true);
React.useEffect(() => {
const unsub = NetInfo.addEventListener((s: { isConnected: boolean | null }) => setIsConnected(!!s.isConnected));
return unsub;
}, []);
return { isConnected };
}
import NetInfo from '@react-native-community/netinfo';
const s = StyleSheet.create({
screen: { flex: 1, backgroundColor: '#0f172a' },
centered: { flex: 1, alignItems: 'center', justifyContent: 'center' },
offlineBanner: { backgroundColor: '#dc2626', paddingVertical: 8, paddingHorizontal: 16 },
offlineText: { color: 'white', textAlign: 'center', fontSize: 13, fontWeight: '600' },
heading: { fontSize: 24, fontWeight: '800', color: '#f1f5f9', marginBottom: 8 },
card: { backgroundColor: '#1e293b', borderRadius: 14, overflow: 'hidden' },
image: { width: '100%', height: 200 },
cardBody: { padding: 16 },
cardTitle: { fontSize: 16, fontWeight: '700', color: '#f1f5f9', marginBottom: 8, lineHeight: 22 },
cardExcerpt: { fontSize: 13, color: '#94a3b8', lineHeight: 18, marginBottom: 12 },
cardFooter: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center' },
author: { fontSize: 12, color: '#229c6b', fontWeight: '600' },
likeBtn: { flexDirection: 'row', alignItems: 'center', gap: 4 },
likeCount: { fontSize: 13, color: '#94a3b8' },
});Tip
Tip
Practice Mini Project News Feed with TanStack Query Offline in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Enterprise news application with automatic background caching and pull-to-refresh
Practice Task
Note
Practice Task - (1) Write a working example of Mini Project News Feed with TanStack Query Offline from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with Mini Project News Feed with TanStack Query Offline is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready react native code.
Finished this lesson?