Skip to content

Instantly share code, notes, and snippets.

@tgmarinho
Created May 4, 2023 15:47
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tgmarinho/76bb097ef507dc46ded495a7eb5297ea to your computer and use it in GitHub Desktop.
Save tgmarinho/76bb097ef507dc46ded495a7eb5297ea to your computer and use it in GitHub Desktop.
prevent memory leak using useEffect and fetch external api
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