การจัดการสถานะกำลังโหลดและข้อผิดพลาด
เพิ่มตัวแปรสถานะ isLoading และข้อผิดพลาด แสดง ActivityIndicator ระหว่างโหลดข้อมูล และแสดงข้อความข้อผิดพลาดที่เข้าใจง่ายเมื่อคำขอล้มเหลว
การจัดการสถานะกำลังโหลดและข้อผิดพลาด เป็นบทเรียน React Native Academy ฟรีบน CoddyKit นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน React Native Academy และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส React Native Academy มีบทเรียนทั้งหมด 4 บทเรียน
บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ
The Three States of Async Data
Every asynchronous data operation has three possible states: loading (the request is in flight), success (data is available), and error (the request failed). A well-built React Native screen handles all three states explicitly, showing the appropriate UI for each. Ignoring any state leads to blank screens, app crashes, or confusing experiences for users.
Defining Loading and Error State Variables
Add isLoading and error state variables alongside your data state. Initialize isLoading to true since the component begins in a loading state before any data has been fetched. Initialize error to null so it is falsy when there is no error.
const [posts, setPosts] = useState([]);
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState(null);Setting States During Fetch
In the fetch logic, reset the error state at the start of each attempt (so a retry clears the previous error), set the data on success, set the error on failure, and always set isLoading to false in the finally block so the spinner stops regardless of the outcome.
const fetchData = async () => {
setIsLoading(true);
setError(null);
try {
const response = await axios.get('/posts');
setPosts(response.data);
} catch (err) {
setError(err.message || 'Something went wrong');
} finally {
setIsLoading(false);
}
};Showing an ActivityIndicator While Loading
Return an ActivityIndicator when isLoading is true. Center it on the screen using a flex container. React Native's ActivityIndicator uses the native platform spinner, matching iOS and Android design conventions automatically.
if (isLoading) {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<ActivityIndicator size='large' color='#6200ee' />
<Text style={{ marginTop: 12, color: '#666' }}>Loading...</Text>
</View>
);
}Showing a User-Friendly Error Message
When error is not null, render an error screen with a clear message and a retry button. Avoid showing raw error objects to users — display a human-readable message instead. The retry button calls the fetch function again, resetting the error and starting a new loading cycle.
if (error) {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center', padding: 24 }}>
<Text style={{ fontSize: 18, marginBottom: 8 }}>Oops!</Text>
<Text style={{ color: '#666', textAlign: 'center', marginBottom: 24 }}>
{error}
</Text>
<Button title='Try Again' onPress={fetchData} />
</View>
);
}Full Component with All Three States
Assemble the complete component: return the loading view when loading, the error view when an error exists, and the data view otherwise. This pattern — early returns for loading and error, then the main content — keeps the JSX clean and readable.
export default function PostsScreen() {
const [posts, setPosts] = useState([]);
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => { fetchData(); }, []);
if (isLoading) return <LoadingView />;
if (error) return <ErrorView message={error} onRetry={fetchData} />;
return <FlatList data={posts} renderItem={renderItem} keyExtractor={(p) => String(p.id)} />;
}Distinguishing Network vs HTTP Errors
Axios throws for both network failures (no internet, timeout) and HTTP errors (4xx, 5xx). Inspect error.response to distinguish them. If error.response exists, the server responded with an error status. If it is undefined, the request never reached the server (network error or timeout).
} catch (err) {
if (err.response) {
// Server responded with 4xx/5xx
const status = err.response.status;
if (status === 404) setError('Content not found');
else if (status === 401) setError('Please log in again');
else setError('Server error: ' + status);
} else {
// No response — network/timeout issue
setError('Network error. Check your connection.');
}
}Displaying Inline Errors in Forms
For form submissions, show the error inline near the submit button rather than replacing the whole screen. Users can then correct their input without navigating away. Use a small error Text component with a red color beneath the submit button, and clear it when the user modifies any field.
function LoginForm() {
const [apiError, setApiError] = useState(null);
const handleSubmit = async () => {
setApiError(null);
try {
await login(email, password);
} catch (err) {
setApiError('Invalid email or password');
}
};
return (
<View>
{/* inputs here */}
{apiError && <Text style={{ color: 'red' }}>{apiError}</Text>}
<Button title='Sign In' onPress={handleSubmit} />
</View>
);
}Loading State for Button Actions
For actions that take time (submitting a form, deleting an item), show a loading indicator inside the button and disable it while the action is in progress. This prevents duplicate submissions and gives the user immediate feedback that the action is being processed.
function SubmitButton({ onPress }) {
const [isSubmitting, setIsSubmitting] = useState(false);
const handlePress = async () => {
setIsSubmitting(true);
await onPress();
setIsSubmitting(false);
};
return (
<TouchableOpacity
onPress={handlePress}
disabled={isSubmitting}
style={[styles.button, isSubmitting && styles.disabledButton]}
>
{isSubmitting
? <ActivityIndicator color='#fff' />
: <Text style={styles.buttonText}>Submit</Text>}
</TouchableOpacity>
);
}Skeleton Loading Screens
Instead of a full-screen spinner, consider showing a skeleton screen — placeholder shapes that mimic the layout of the real content. This pattern (used by Facebook, LinkedIn, YouTube) gives a better perceived performance because users see the structure of the content immediately, even before the data loads.
function SkeletonRow() {
return (
<View style={styles.skeletonRow}>
<View style={styles.skeletonAvatar} />
<View style={{ flex: 1 }}>
<View style={styles.skeletonLine} />
<View style={[styles.skeletonLine, { width: '60%' }]} />
</View>
</View>
);
}
if (isLoading) return <FlatList data={[1,2,3,4,5]} renderItem={() => <SkeletonRow />} keyExtractor={(i) => String(i)} />;Toasts and Snackbars for Non-Critical Errors
Not every error warrants a full error screen. For transient errors that the user can recover from (like a failed background refresh), use a toast notification or snackbar that appears briefly at the bottom of the screen. Libraries like react-native-toast-message provide ready-made toast components for React Native.
import Toast from 'react-native-toast-message';
// On a background refresh failure:
Toast.show({
type: 'error',
text1: 'Could not refresh',
text2: 'Showing cached data',
visibilityTime: 3000,
});Quick Check
Test your understanding of handling loading and error states from this lesson.
Lesson Recap
In this lesson you learned: track isLoading and error as separate state variables alongside your data, use ActivityIndicator for full-screen loading and inline error text for form errors, and always call setIsLoading(false) in a finally block so the spinner stops in all cases. Next up we cover POST, PUT, and DELETE requests with Axios.
คำถามที่พบบ่อย
บทเรียน “การจัดการสถานะกำลังโหลดและข้อผิดพลาด” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “การจัดการสถานะกำลังโหลดและข้อผิดพลาด” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส React Native Academy ให้อัปเกรดเป็น CoddyKit PRO คอร์ส React Native Academy มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “การจัดการสถานะกำลังโหลดและข้อผิดพลาด”
เพิ่มตัวแปรสถานะ isLoading และข้อผิดพลาด แสดง ActivityIndicator ระหว่างโหลดข้อมูล และแสดงข้อความข้อผิดพลาดที่เข้าใจง่ายเมื่อคำขอล้มเหลว คุณปฏิบัติ 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 ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- ฮุก useEffect และอาร์เรย์การพึ่งพา
- การส่งคำขอ GET ด้วย Axios
- การจัดการสถานะกำลังโหลดและข้อผิดพลาด
- POST, PUT และ DELETE ด้วย Axios