Lesson 2
Navigating Error Handling and Fetch States in React Functional Components
Topic Overview and Actualization

Hello! Today, we're delving into Error Handling and Fetch States in React Functional Components. Our mission? To prepare ourselves for potential errors during API calls, much like a postman prepares for potential issues during mail delivery.

Handling API Errors in React

API calls can fail due to network errors such as internet disconnections or server downtime, or HTTP status errors, which include the 400 series for client-side errors and the 500 series for server-side errors.

Let's add error handling to our Fetch API call and manage state changes using the useState hook. Providing a fallback UI for error scenarios can greatly enhance the user experience:

JavaScript
1function App() { 2 const [data, setData] = useState(null); 3 const [error, setError] = useState(null); // initialize an error state 4 5 useEffect(() => { 6 fetch('https://api-regional.codesignalcontent.com/posting-application-2/posts/') 7 .then(response => { // If response is not ok, throw an error, otherwise parse the data to JSON 8 if (!response.ok) { throw Error(response.statusText); } 9 return response.json(); 10 }) 11 .then(data => setData(data)) 12 .catch(error => setError(error)); // If error occurred, set it to state 13 }, []); 14 15 return ( {/* Render an error message if it occurs, otherwise render fetched data or loading message */} 16 <div className="App"> 17 {error ? <p>{error.message}</p> : data ? <p>Data fetched successfully!</p> : 'Loading...'} 18 </div> 19 ); 20}
Retry Mechanisms

A retry mechanism helps to recover from temporary failures. The principle is simple: if a request fails, try it again. Here's our React component enhanced with a retry mechanism:

JavaScript
1function App() { 2 const [data, setData] = useState(null); 3 const [error, setError] = useState(null); 4 const [retries, setRetries] = useState(0); 5 6 useEffect(() => { 7 if (retries < 3) { // Limit the number of retries to 3 8 fetch('https://api-regional.codesignalcontent.com/posting-application-2/posts/') 9 .then(response => { 10 if (!response.ok) { throw Error(response.statusText); } 11 return response.json(); 12 }) 13 .then(data => setData(data)) 14 .catch(error => { 15 setError(error); 16 setRetries(retries + 1); // Increment the number of retries if an error occurs 17 }); 18 } 19 }, [retries]); // Rerun the effect if retries number changed 20 21 // return JSX similar to the previous block 22}
Lesson Summary and Practice

Excellent! We've explored React's functional components, API errors, and how to respond to them. Next up, we have some exercises where you can apply your new knowledge. Keep practicing because, like postmen, there's always mail to deliver, and for us, there are always APIs to call! Until our next adventure - excellent work!

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.