Lesson 9 of 9
Practice & Quiz - Networking & Data Fetching
Test your knowledge of TanStack Query offline caching, file uploads with FormData, WebSocket management, and Axios interceptors with a practical exercise and 5 quiz questions.
Practical Exercise - Offline-Aware TanStack Query Feed
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { onlineManager } from '@tanstack/react-query';
import NetInfo from '@react-native-community/netinfo';
import { useEffect } from 'react';
import axios from 'axios';
import { View, Text, FlatList, Pressable, ActivityIndicator } from 'react-native';
// โโโ Configure TanStack Query online status via NetInfo โโโโโโโโ
// This integrates device network state with React Query's refetch behavior
export function useOnlineManager() {
useEffect(() => {
const unsubscribe = NetInfo.addEventListener(state => {
onlineManager.setOnline(
state.isConnected != null &&
state.isConnected &&
Boolean(state.isInternetReachable)
);
});
return unsubscribe;
}, []);
}
// โโโ API โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
interface Post { id: number; title: string; userId: number; }
const api = axios.create({ baseURL: 'https://jsonplaceholder.typicode.com' });
// โโโ Query with offline persistence โโโโโโโโโโโโโโโโโโโโโโโโโโโ
function usePosts() {
return useQuery<Post[]>({
queryKey: ['posts'],
queryFn: () => api.get('/posts?_limit=10').then(r => r.data),
staleTime: 5 * 60_000, // fresh for 5 minutes
gcTime: 24 * 60 * 60_000, // keep in cache for 24h (survives app restart with persistQueryClient)
retry: 3,
retryDelay: attempt => Math.min(1000 * 2 ** attempt, 30_000), // exponential backoff
});
}
// โโโ Mutation with optimistic update โโโโโโโโโโโโโโโโโโโโโโโโโ
function useLikePost() {
const qc = useQueryClient();
return useMutation({
mutationFn: (postId: number) => api.post(`/posts/${postId}/like`),
onMutate: async (postId) => {
await qc.cancelQueries({ queryKey: ['posts'] });
const prev = qc.getQueryData<Post[]>(['posts']);
// Optimistic: add liked flag immediately
qc.setQueryData<Post[]>(['posts'], old =>
old?.map(p => p.id === postId ? { ...p, liked: true } : p) ?? []
);
return { prev };
},
onError: (_, __, ctx) => ctx?.prev && qc.setQueryData(['posts'], ctx.prev),
onSettled: () => qc.invalidateQueries({ queryKey: ['posts'] }),
});
}
// โโโ Component โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
export function PostFeed() {
useOnlineManager(); // wire NetInfo to React Query
const { data, isLoading, isError, isFetching } = usePosts();
const like = useLikePost();
if (isLoading) return <ActivityIndicator style={{ flex: 1 }} />;
if (isError) return <Text style={{ padding: 16, color: '#ef4444' }}>Failed to load - showing cached data</Text>;
return (
<FlatList
data={data}
keyExtractor={item => String(item.id)}
ListHeaderComponent={isFetching ? <Text style={{ textAlign: 'center', padding: 8 }}>Updating...</Text> : null}
renderItem={({ item }) => (
<View style={{ padding: 16, borderBottomWidth: 1, borderColor: '#f0f0f0' }}>
<Text style={{ fontWeight: '600' }}>{item.title}</Text>
<Pressable onPress={() => like.mutate(item.id)} style={{ marginTop: 8 }}>
<Text style={{ color: '#229c6b' }}>๐ Like</Text>
</Pressable>
</View>
)}
/>
);
}Module Quiz
How does TanStack Query's `onlineManager` integrate with React Native's network state?
Tip
Tip
Practice Practice Quiz Networking Data Fetching in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Module 7 Knowledge Check: Axios, TanStack Query, offline syncing, and WebSockets
Practice Task
Note
Practice Task - (1) Write a working example of Practice Quiz Networking Data Fetching 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.
Common Mistake
Warning
A common mistake with Practice Quiz Networking Data Fetching 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?