Created
May 4, 2023 15:47
-
-
Save tgmarinho/76bb097ef507dc46ded495a7eb5297ea to your computer and use it in GitHub Desktop.
prevent memory leak using useEffect and fetch external api
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useState, useEffect } from 'react'; | |
function FetchData() { | |
const [data, setData] = useState(null); | |
const [error, setError] = useState(null); | |
useEffect(() => { | |
// Create a new AbortController instance | |
const abortController = new AbortController(); | |
const signal = abortController.signal; | |
const fetchData = async () => { | |
try { | |
const response = await fetch('https://api.example.com/data', { signal }); | |
if (!response.ok) { | |
throw new Error(`Error: ${response.status}`); | |
} | |
const responseData = await response.json(); | |
setData(responseData); | |
} catch (error) { | |
// Only set the error state if the error is not due to the fetch being aborted | |
if (!signal.aborted) { | |
setError(error); | |
} | |
} | |
}; | |
fetchData(); | |
// Cleanup function that will be called when the component is unmounted | |
return () => { | |
abortController.abort(); | |
}; | |
}, []); // Empty dependency array to only run the effect on mount and unmount | |
if (error) { | |
return <div>Error: {error.message}</div>; | |
} | |
if (!data) { | |
return <div>Loading...</div>; | |
} | |
return ( | |
<div> | |
<h1>Data</h1> | |
{/* Render the data as needed */} | |
</div> | |
); | |
} | |
export default FetchData; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment