🤔Imagine you're fetching data in a React app, and the user navigates away before it's complete. How do you gracefully handle this scenario to avoid potential issues? 🔄 Share your thoughts and best practices! 💡
My Answer📝
Certainly! Below is an example of handling this scenario in a React component. This example uses functional components and hooks, including the useEffect hook to handle the cleanup when the component is unmounted.
import React, { useState, useEffect } from 'react';
const ProductFetchComponent = () => {
const [products, setProducts] = useState([]);
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
const abortController = new AbortController();
useEffect(() => {
const fetchData = async () => {
try {
setLoading(true);
const response = await fetch('https://dummyjson.com/products', {
signal: abortController.signal,
method: 'GET', // Adjust the method if needed
// Other fetch options...
});
const data = await response.json();
// Process the data as needed
setProducts(data);
setLoading(false);
} catch (error) {
if (error.name === 'AbortError') {
console.log('Fetch aborted');
} else {
setError(error.message);
setLoading(false);
}
}
};
fetchData();
// Cleanup function to abort the fetch when the component is unmounted
return () => abortController.abort();
}, []); // Empty dependency array ensures the effect runs only once
return (
<div>
<h1>Product List</h1>
{loading && <p>Loading...</p>}
{error && <p>Error: {error}</p>}
<ul>
{products.map(product => (
<li key={product.id}>{product.name}</li>
))}
</ul>
</div>
);
};
export default ProductFetchComponent;
This React component uses the useEffect hook to trigger the fetch when the component mounts. The abortController is created and used to handle the abort signal for the fetch request. The cleanup function in the useEffect hook ensures that if the component is unmounted (or when the component is about to be unmounted), it aborts the ongoing fetch request to avoid potential memory leaks.
Top comments (0)