Handling Loading and Error States
Add isLoading and error state variables, show an ActivityIndicator while data loads, and display a user-friendly error message when the request fails.
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);All lessons in this course
- The useEffect Hook and Dependency Arrays
- Making GET Requests with Axios
- Handling Loading and Error States
- POST, PUT, and DELETE with Axios