Skip to main content

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.

10 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Practical Exercise - Offline-Aware TanStack Query Feed

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

Module Quiz
Question 1 of 5

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.

Diagram
Loading diagramโ€ฆ

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.

Topics in This Module

0/9 done