ฟีเจอร์หลัก: ฟีดข้อมูลพร้อมการรองรับการใช้งานออฟไลน์
สร้างฟีดข้อมูลหลักโดยใช้ React Query พร้อมการคงข้อมูลสำหรับการใช้งานออฟไลน์ ใช้การดึงเพื่อรีเฟรชและการแบ่งหน้า เพิ่มการเปลี่ยนแปลงข้อมูลสำหรับการสร้างและลบรายการ และทำให้รายการเคลื่อนไหวขณะปรากฏ
ฟีเจอร์หลัก: ฟีดข้อมูลพร้อมการรองรับการใช้งานออฟไลน์ เป็นบทเรียน React Native Academy ฟรีบน CoddyKit นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน React Native Academy และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส React Native Academy มีบทเรียนทั้งหมด 4 บทเรียน
บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ
What Is Offline-First Design
Offline-first design means the app works correctly without an internet connection — users can view cached data, perform mutations that queue for sync, and experience no error messages just because the network is unavailable. Mobile users frequently move in and out of connectivity. A React Native app that breaks without a network feels fragile; one that keeps working feels polished and reliable.
Setting Up the QueryClient
React Query's QueryClient is the backbone of the data layer. Configure it with sensible defaults: a staleTime that avoids unnecessary refetches (e.g., 5 minutes for data that changes infrequently), and a gcTime (garbage collection time) that keeps unused data in the cache long enough to serve it from cache on reconnect. Pass this client to QueryClientProvider at the app root.
// src/services/queryClient.ts
import { QueryClient } from '@tanstack/react-query';
export const queryClient = new QueryClient({
defaultOptions: {
queries: {
staleTime: 1000 * 60 * 5, // 5 minutes — don't refetch too often
gcTime: 1000 * 60 * 60, // Keep in cache 1 hour after unmount
retry: 2,
retryDelay: (attempt) => Math.min(1000 * 2 ** attempt, 30000),
refetchOnWindowFocus: false, // Not needed on mobile
refetchOnReconnect: true, // Sync when network returns
},
},
});Persisting the Query Cache with AsyncStorage
To make data available when offline, persist the React Query cache to AsyncStorage. Use @tanstack/react-query-persist-client with an AsyncStorage persister. On app startup, the persisted cache is restored before the first network request — so users see their habits list immediately, even before the fetch completes. The cache is hydrated asynchronously, so show cached data optimistically and update when the fresh data arrives.
// App.tsx
import { PersistQueryClientProvider } from '@tanstack/react-query-persist-client';
import { createAsyncStoragePersister } from '@tanstack/query-async-storage-persister';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { queryClient } from './src/services/queryClient';
const asyncStoragePersister = createAsyncStoragePersister({
storage: AsyncStorage,
key: 'REACT_QUERY_CACHE',
});
export default function App() {
return (
<PersistQueryClientProvider
client={queryClient}
persistOptions={{ persister: asyncStoragePersister }}
>
<AuthProvider>
<RootNavigator />
</AuthProvider>
</PersistQueryClientProvider>
);
}Fetching the Habits List with useQuery
Build a custom hook useHabits that encapsulates the Supabase query inside useQuery. The query key ['habits', userId] scopes the cache to the current user, preventing data from leaking between accounts. React Query returns data, isLoading, and error — pass all three to the screen to show the correct UI state at each point.
// src/hooks/useHabits.ts
import { useQuery } from '@tanstack/react-query';
import { supabase } from '../services/supabase';
import { useAuth } from '../context/AuthContext';
import { Habit } from '../types';
async function fetchHabits(userId: string): Promise<Habit[]> {
const { data, error } = await supabase
.from('habits')
.select('*')
.eq('user_id', userId)
.order('created_at', { ascending: true });
if (error) throw error;
return data;
}
export function useHabits() {
const { session } = useAuth();
const userId = session!.user.id;
return useQuery({
queryKey: ['habits', userId],
queryFn: () => fetchHabits(userId),
enabled: !!userId,
});
}Rendering the FlatList with Cached Data
Use the useHabits hook in the HabitList screen. Show a skeleton loader or spinner for the initial load, use the data array directly as the FlatList source, and handle the error state with a retry button. Because the cache is persisted, on subsequent app launches data is immediately available (no loading flash) while React Query fetches a fresh version in the background.
// src/screens/habits/HabitListScreen.tsx
import { FlatList, ActivityIndicator, View, Text } from 'react-native';
import { useHabits } from '../../hooks/useHabits';
import { HabitCard } from '../../components/HabitCard';
export function HabitListScreen() {
const { data: habits, isLoading, error, refetch } = useHabits();
if (isLoading && !habits) {
return <ActivityIndicator style={{ flex: 1 }} />;
}
if (error) {
return (
<View>
<Text>Failed to load habits.</Text>
<Button title='Retry' onPress={() => refetch()} />
</View>
);
}
return (
<FlatList
data={habits}
keyExtractor={(item) => item.id}
renderItem={({ item }) => <HabitCard habit={item} />}
onRefresh={refetch}
refreshing={isLoading}
/>
);
}Creating Habits with useMutation
useMutation handles the insert operation. On onSuccess, call queryClient.invalidateQueries(['habits', userId]) to trigger a fresh fetch of the habits list. This ensures the newly created habit appears in the list immediately after creation without manually updating the cache. Set onError to show the user an error message if the insert fails.
// src/hooks/useCreateHabit.ts
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { supabase } from '../services/supabase';
import { useAuth } from '../context/AuthContext';
export function useCreateHabit() {
const queryClient = useQueryClient();
const { session } = useAuth();
const userId = session!.user.id;
return useMutation({
mutationFn: async ({ name, icon, color }) => {
const { error } = await supabase.from('habits').insert({
user_id: userId,
name,
icon,
color,
});
if (error) throw error;
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['habits', userId] });
},
onError: (error) => {
Alert.alert('Error', error.message);
},
});
}Optimistic Updates for Check-In
For the daily check-in (marking a habit as done), use optimistic updates to update the UI instantly before the network request completes. When the user taps the check-in button, immediately update the cache with the assumed result. If the request fails, roll back the cache to the previous state. This makes the app feel instant even on slow networks.
// Optimistic update pattern with useMutation
const toggleCompletion = useMutation({
mutationFn: (habitId) => insertCompletion(habitId, today),
onMutate: async (habitId) => {
// Cancel in-flight refetches
await queryClient.cancelQueries({ queryKey: ['completions', userId] });
// Save snapshot for rollback
const previous = queryClient.getQueryData(['completions', userId]);
// Optimistically add completion
queryClient.setQueryData(['completions', userId], (old) => [
...old,
{ habit_id: habitId, completed_date: today }
]);
return { previous }; // Pass snapshot to onError
},
onError: (_err, _habitId, context) => {
// Roll back on failure
queryClient.setQueryData(['completions', userId], context.previous);
},
onSettled: () => {
queryClient.invalidateQueries({ queryKey: ['completions', userId] });
},
});Network Status and Offline Banner
Show users a subtle offline banner when the device has no internet connection so they understand why their changes haven't synced. Use @react-native-community/netinfo to listen for connectivity changes. React Query automatically pauses mutations when offline and retries them when connectivity returns — the banner simply makes this behavior visible to the user.
import NetInfo from '@react-native-community/netinfo';
import { useEffect, useState } from 'react';
export function OfflineBanner() {
const [isOffline, setIsOffline] = useState(false);
useEffect(() => {
const unsubscribe = NetInfo.addEventListener((state) => {
setIsOffline(!state.isConnected);
});
return unsubscribe;
}, []);
if (!isOffline) return null;
return (
<View style={{
backgroundColor: '#FF3B30',
padding: 8,
alignItems: 'center'
}}>
<Text style={{ color: 'white', fontWeight: 'bold' }}>
No internet connection — changes will sync when online
</Text>
</View>
);
}Pagination with FlatList and useInfiniteQuery
For feeds with many items, implement pagination using useInfiniteQuery. It fetches pages of data and appends them to a running list. Pass fetchNextPage to FlatList's onEndReached handler so the next page loads automatically as the user scrolls. Use getNextPageParam to derive the next page cursor from the last page's response.
import { useInfiniteQuery } from '@tanstack/react-query';
export function useHabitsPaginated() {
return useInfiniteQuery({
queryKey: ['habits', 'paginated'],
queryFn: ({ pageParam = 0 }) =>
supabase.from('habits').select('*')
.range(pageParam, pageParam + 19), // 20 per page
getNextPageParam: (lastPage, allPages) => {
const nextOffset = allPages.length * 20;
return lastPage.data?.length === 20 ? nextOffset : undefined;
},
initialPageParam: 0,
});
}
// In screen:
const { data, fetchNextPage, hasNextPage } = useHabitsPaginated();
const habits = data?.pages.flatMap(p => p.data) ?? [];
<FlatList
data={habits}
onEndReached={() => hasNextPage && fetchNextPage()}
onEndReachedThreshold={0.3}
/>Animating List Item Entry
Make the feed feel dynamic by animating items as they appear. A simple fade-in + slide-up on mount using the Animated API adds polish without heavy libraries. Create a reusable AnimatedListItem wrapper that each item passes through. The animation runs once on mount — use useRef to prevent re-triggering on re-renders.
import { useRef, useEffect } from 'react';
import { Animated } from 'react-native';
export function AnimatedListItem({ children, index }) {
const opacity = useRef(new Animated.Value(0)).current;
const translateY = useRef(new Animated.Value(20)).current;
useEffect(() => {
Animated.parallel([
Animated.timing(opacity, {
toValue: 1,
duration: 300,
delay: index * 50, // Stagger by index
useNativeDriver: true,
}),
Animated.timing(translateY, {
toValue: 0,
duration: 300,
delay: index * 50,
useNativeDriver: true,
}),
]).start();
}, []);
return (
<Animated.View style={{ opacity, transform: [{ translateY }] }}>
{children}
</Animated.View>
);
}Streak Calculation Logic
The streak is the number of consecutive days a habit was completed up to and including today. Calculate it in JavaScript from the completions array. Sort completions by date descending, start from today and walk backwards, counting consecutive days. This logic is pure JavaScript — no network call needed if the completions are already in the React Query cache.
// src/utils/streaks.ts
export function calculateStreak(completedDates: string[]): number {
if (completedDates.length === 0) return 0;
const sorted = [...completedDates].sort().reverse();
const today = new Date().toISOString().split('T')[0];
let streak = 0;
let current = new Date(today);
for (const dateStr of sorted) {
const expected = current.toISOString().split('T')[0];
if (dateStr === expected) {
streak++;
current.setDate(current.getDate() - 1);
} else if (dateStr < expected) {
break; // Gap found
}
}
return streak;
}
// Usage:
const streak = calculateStreak(
completions
.filter(c => c.habit_id === habit.id)
.map(c => c.completed_date)
);Quick Check
Test your understanding of React Native Mobile Development concepts from this lesson.
Lesson Recap
In this lesson you learned: how to configure React Query with persistence to serve cached data while offline, how to build custom hooks with useQuery and useMutation for habits CRUD, and how to implement optimistic updates for immediate UI feedback. You also saw how to add pagination, entry animations, and streak calculation from cached data. Next up we polish, test, and ship to both stores.
คำถามที่พบบ่อย
บทเรียน “ฟีเจอร์หลัก: ฟีดข้อมูลพร้อมการรองรับการใช้งานออฟไลน์” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “ฟีเจอร์หลัก: ฟีดข้อมูลพร้อมการรองรับการใช้งานออฟไลน์” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส React Native Academy ให้อัปเกรดเป็น CoddyKit PRO คอร์ส React Native Academy มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “ฟีเจอร์หลัก: ฟีดข้อมูลพร้อมการรองรับการใช้งานออฟไลน์”
สร้างฟีดข้อมูลหลักโดยใช้ React Query พร้อมการคงข้อมูลสำหรับการใช้งานออฟไลน์ ใช้การดึงเพื่อรีเฟรชและการแบ่งหน้า เพิ่มการเปลี่ยนแปลงข้อมูลสำหรับการสร้างและลบรายการ และทำให้รายการเคลื่อนไหวขณะปรากฏ คุณปฏิบัติ React Native Academy ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน React Native Academy หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน React Native Academy บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน
บทเรียน “ฟีเจอร์หลัก: ฟีดข้อมูลพร้อมการรองรับการใช้งานออฟไลน์” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน React Native Academy นี้ได้ไหม
ได้ บทเรียน React Native Academy ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- การวางแผนสถาปัตยกรรมและชุดเทคโนโลยี
- ขั้นตอนการยืนยันตัวตนและเส้นทางที่มีการป้องกัน
- ฟีเจอร์หลัก: ฟีดข้อมูลพร้อมการรองรับการใช้งานออฟไลน์
- ปรับแต่ง ทดสอบ และเผยแพร่ไปยังทั้งสองสโตร์