-
- Notifications
You must be signed in to change notification settings - Fork 116
Description
When returning abort as the useEffect cleanup function, the request aborts and the promise resolves as expected, but I still see the React warning: Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function. in Test (at App.js:15)
Question: How do I cancel a fetch on unmount (and not receive the React warning)?
In case this Codesandbox link expires, I'll paste the code below. I tried to keep it simple -- one component unmounts another component before its fetch finishes
App.js - unmount <Test /> after 100ms (to interrupt the API call made by <Test />)
import Test from "./Test"; import "./styles.css"; export default function App() { const [bool, setBool] = useState(true); // 100ms after mounting, set bool to false useEffect(() => { setTimeout(() => { setBool(false); }, 100); }, []); return <div className="App">{bool && <Test />}</div>; } Test.js - Make an API call using useFetch, and return abort from useEffect
import useFetch from "use-http"; export default function Test() { const { get, abort } = useFetch( "https://jsonplaceholder.typicode.com/posts/1" ); const loadIt = async () => await get(); useEffect(() => { loadIt(); return abort; }, []); return <h1>I am here</h1>; }