Reputation: 21
i have very strange problem my console return 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.
i readed on topics here i and tryed alot of solutions with unmounted example true and false but i didnt solve my problem heres the code:
const [getCompany, setgetCompany] = useState('');
useEffect(() => {
const fetchCompany = async () => {
try {
const responseData = await sendRequest(
`http://localhost:5000/api/companies/${props.company}`,
);
setgetCompany(responseData);
} catch (err) {}
};
props.company && fetchCompany();
}, [props.company]);
and in return i did this:
{(() => {
if(getCompany){
return Object.keys(getCompany).map((item,index) => {
return(
<img
key={getCompany[item].id}
src={`http://localhost:5000/${getCompany[item].image}`}
alt={getCompany[item].title}
/>
)
})
}
})()}
this is just function to get details from companies like photo, any help?
Upvotes: 0
Views: 469
Reputation: 1597
You need to cancel your promise & request somehow when unmounting. Here is a generic json fetch example with async task cancellation. The network request will be aborted, not just ignored the result (Live demo):
import React, { useEffect, useState } from "react";
import { CPromise, CanceledError } from "c-promise2";
import cpFetch from "cp-fetch";
function MyComponent(props) {
const [text, setText] = useState("fetching...");
useEffect(() => {
console.log("mount");
const promise = CPromise.from(function* () {
try {
const response = yield cpFetch(props.url);
const json = yield response.json();
setText(`Success: ${JSON.stringify(json)}`);
} catch (err) {
console.warn(err);
CanceledError.rethrow(err); //passthrough
// handle other errors than CanceledError
setText(`Failed: ${err}`);
}
}, []);
return () => {
console.log("unmount");
promise.cancel();
};
}, [props.url]);
return <p>{text}</p>;
}
Upvotes: 1