Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Cleanup function after a fetch call in React

const[imageContainer,setImageContainer] = useState([])
    const navigate = useNavigate();
    useEffect(()=>{
        Promise.all([
            fetch("https://www.themealdb.com/api/json/v1/1/random.php").then(response=>response.json()),
            fetch("https://www.themealdb.com/api/json/v1/1/random.php").then(response=>response.json()),
            fetch("https://www.themealdb.com/api/json/v1/1/random.php").then(response=>response.json()),
            fetch("https://www.themealdb.com/api/json/v1/1/random.php").then(response=>response.json()),
            fetch("https://www.themealdb.com/api/json/v1/1/random.php").then(response=>response.json()),
          ]).then(response=>setImageContainer(response.map(recipe=>{
            return recipe.meals[0]
          })))
    },[])

Hello, I’m relatively new to React. So far I’ve learned that you should always clean up after using useEffect with the return function to not slow down your application. But I’m not sure how to do that after a fetch call.

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Cleanup in effect is usually for subscriptions (like event handlers), timers or other side-effects; it’s done to prevent memory leaks. However with fetch calls, it’s different. It’s more about cancelling the requests if the component unmounts before the requests are complete to avoid setting the state on an unmounted component.

This is how you should handle fetch request cleanup:

useEffect(() => {
    const controller = new AbortController();
    const signal = controller.signal;

    Promise.all([
        fetch("https://www.themealdb.com/api/json/v1/1/random.php", { signal }).then(response => response.json()),
        fetch("https://www.themealdb.com/api/json/v1/1/random.php", { signal }).then(response => response.json()),
        fetch("https://www.themealdb.com/api/json/v1/1/random.php", { signal }).then(response => response.json()),
        fetch("https://www.themealdb.com/api/json/v1/1/random.php", { signal }).then(response => response.json()),
        fetch("https://www.themealdb.com/api/json/v1/1/random.php", { signal }).then(response => response.json()),
    ]).then(response => setImageContainer(response.map(recipe => recipe.meals[0])))
     .catch(error => {
         if (error.name === 'AbortError') {
             console.log('Fetch aborted');
         } else {
             console.error('Fetch error:', error);
         }
     });

    return () => {
        controller.abort(); // This will cancel the fetch requests when the component unmounts
    };
}, []);

Uses AbortController, and its signal is passed to each fetch request. controller.abort(); is executed inside the return function of useEffect.

Reffer:

AbortController

useEffects

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading