Testing useEffect cleanup with Firebase - reactjs

I was getting this error
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.
and read in multiple places that one way to avoid such an error when using firebase is to do something like this:
useEffect(() => {
let isMounted = true;
const fetchImages = async () => {
const response = fire
.firestore()
.collection("albums/" + unique + "/images"); //unique is the name of the album, passed on as a prop to this component
const data = await response.get();
const Imagearray = [];
data.docs.forEach((item) => {
Imagearray.push({ id: item.id, original: item.data().url });
});
if (isMounted) setImages(Imagearray);
};
fetchImages();
return () => {
isMounted = false;
};
}, []);
(Copied from this answer)
How do I test whether or not the state gets updated in React Testing Library when the component is unmounted? Is this even something I should worry about testing? I tried using unmount(), but then of course I couldn't test for any of the changes caused when the state updates because the component was unmounted.

Related

Trying to implement a cleanup in a useEffect to prevent no-op memory leak error

I am trying to update a piece of UI based on a conditional. The conditional is set by a database call in a separate component. It sometimes works, but often doesn't. When it doesn't work, it gets this error:
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 have followed other advice and tried to do a cleanup in a useEffect:
const [isPatched, setIsPatched] = useState<boolean>(false);
useEffect(() => {
x.Log ? setPatched(true) : setPatched(false);
return () => {
setIsPatched(false);
};
}, []);
const setPatched = (patched: boolean) => {
setIsPatched(patched);
};
Other component db call:
useEffect(() => {
if (disabled === true) {
const handle = setTimeout(() => setDisabled(false), 7000);
return () => clearTimeout(handle);
}
}, [disabled]);
function handleClick() {
[...]
const updatePatchedX = async (id: string) => {
//check if patched x already in db
const content = await services.xData.getxContent(id);
const xyToUpdated = content?.p[0] as T;
if (!xToUpdated.log) {
// add log property to indicate it is patched and put in DB
xToUpdated.log = [
{ cId: cId ?? "", uId: uId, appliedAt: Date.now() },
];
if (content) {
await services.xData
.updateOTxBook(id, content, uId)
.then(() => {
console.log("done");
setPatched(true);
setDisabled(true);
});
}
}
};
updatePatchedX(notebookID);
}
The UI is only fixed on refresh - not immediately, as the useEffect is supposed to achieve? Not sure where to go from here. Could be a race condition?
I have experienced this in the past and here's what I learned from it
This is normally caused by this sequence of events:
user clicks button => triggers API call => UI changes and the button gets unmounted => API call finishes and tries to update the state of a component that has been unmounted
If the action could be canceled then the default recommendation of "To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function." makes sense; but in this case the API call cannot be cancelled.
The only solution I've found to this is using a ref to track whether the component has been unmounted by the time the API call completes
Below a snippet with just the relevant changes for simplicity
const mainRef = useRef(null);
function handleClick() {
[...]
const updatePatchedX = async (id: string) => {
...
await services.xData
.updateOTxBook(id, content, uId)
.then(() => {
if (mainRef.current) {
console.log("done");
setPatched(true);
setDisabled(true);
}
});
...
};
updatePatchedX(notebookID);
}
return (
<div ref={mainRef}>.... <button onClick={handleClick}>...</button></div>
);
The above works because when the component gets unmounted the myRef references get emptied but you can still check its value when the API call eventually fulfills and before you use some setState function

How to cancel asynchronous tasks in a useEffect cleanup function?

I am getting this error:
index.js:1 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.
index.js:1 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.
at Products (http://localhost:3000/static/js/main.chunk.js:2779:5)
at div
at Home
at RenderedRoute (http://localhost:3000/static/js/vendors~main.chunk.js:246119:5)
at Routes (http://localhost:3000/static/js/vendors~main.chunk.js:246568:5)
at Router (http://localhost:3000/static/js/vendors~main.chunk.js:246499:15)
at BrowserRouter (http://localhost:3000/static/js/vendors~main.chunk.js:244709:5)
at div
at App
I assume the problem is here:
Products.js
const [products, setProducts] = useState([]);
useEffect(() => {
const getProdcuts = async () => {
try {
const res = await axios.get(
category
? `http://localhost:5000/e-mart/products?category=${category}`
: `http://localhost:5000/e-mart/products`
);
setProducts(res.data);
} catch (err) {
console.log(err.message);
}
};
getProdcuts();
}, [category]);
My home page is not loading. No problem is shown in the terminal. How can I resolve this?
You can use the AbortController to abort an async request, it'd look like
useEffect(() => {
const abortController = new AbortController();
const getProdcuts = async () => {
try {
const res = await axios.get(
category
? `http://localhost:5000/e-mart/products?category=${category}`
: `http://localhost:5000/e-mart/products`,
{ signal: abortController .signal } // Notice this line here
);
setProducts(res.data);
} catch (err) {
console.log(err.message);
}
};
getProdcuts();
return () => {
// Function returned from useEffect is called on unmount
// Here it'll abort the fetch
abortController.abort();
}
}, [category]);
That's a quick way to fix this problem but if you're not sure why this problem is happening in the first place it's probably because you're not expecting Products to unmount.
You might have a parent component rendering Products or one of its parents conditionnally and a state change cause an unmount before fetch is done.

Expo React 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

I'm new to react native and was following a tutorial on medium about how to connect with firebase auth. Everything seems to work fine, but I keep getting this warning below:
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 pretty much did exactly what was said in the tutorial and tried out a few other things to fix it, but nothing seems to work. Here is the code it's pointing the error to:
let currentUserUID = firebase.auth().currentUser.uid;
const [firstName, setFirstName] = useState('');
useEffect(() => {
getUserInfo();
})
async function getUserInfo(){
try {
let doc = await firebase
.firestore()
.collection('users')
.doc(currentUserUID)
.get();
if (!doc.exists){
Alert.alert('No user data found!')
} else {
let dataObj = doc.data();
setFirstName(dataObj.firstName)
}
} catch (err){
Alert.alert('There is an error.', err.message)
}
}
It would be great if anyone could help me fix this problem and explain what exactly has gone wrong.
This is the link to the tutorial I was following:
The issue here is that you are potentially enqueueing a state update after a component has unmounted. Since you are accessing your firestore directly, asynchronously, you can use a React ref to track if the component is still mounted before enqueuing the update.
const isMountedRef = React.ref(null);
useEffect(() => {
isMountedRef.current = true; // set true when mounted
return () => isMountedRef.current = false; // clear when unmounted
}, []);
useEffect(() => {
async function getUserInfo(){
try {
let doc = await firebase
.firestore()
.collection('users')
.doc(currentUserUID)
.get();
if (!doc.exists){
Alert.alert('No user data found!')
} else {
let dataObj = doc.data();
if (isMountedRef.current) { // <-- check if still mounted
setFirstName(dataObj.firstName);
}
}
} catch (err){
Alert.alert('There is an error.', err.message)
}
}
getUserInfo();
}, []); // <-- include dependency array, empty to run once when mounting
Your getInfoUser() function is async. You should do something like this in useEffect:
useEffect(async () => { await getUserInfo(); }, [])
As a second argument in useEffect use the dependency array. Using the dependency array is equivalent with componentDidMount.
Your effect will take place only once when the component is first rendered. Additionally there are cases when you need to provide a cleanup function in useEffect something like this:
return () => {
//do something or cancel a subscription
}

React native: How to prevent memory leak caused by updating state on unmounted component.State is updated after receiving an api response?

Is the solution below actually preventing memory leaks on the react-native App or just hiding the warning?
Is there any other solution for fixing this issue other than the solution below.
I found a way to prevent the state update on API response. By using useRef like below
const _isMounted = useRef(true); // Initial value _isMounted = true
useEffect(() => {
_isMounted.current = true;
return () => {
_isMounted.current = false;
}
}, []);
const onResponse = () => {
if (_isMounted.current) {
setResponse(data);
}
}
Is there any other solution for fixing this issue? I use redux-saga to handle API.
In redux-saga, I pass a callback. The code gives me a warning state is updated after unmounting
const [isSubmitting, setSubmitting] = useState(false); // this state is used to disable submit button and show loader
props.saveData({
token: props.login_token,
setSubmitting: setSubmitting,
data: data
});
Solution
props.saveData({
token: props.login_token,
setSubmitting: (flag)=>{
if(_isMounted.current){
setSubmitting(flag);
}
},
data: data
});
Another solution I found was to cancel Axios but I don't want to cancel a POST operation.

error: react state update on an unmounted component, not sure how to solve

So I am getting the error
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.
const [loggedinUser, setLoggedInUser] = React.useState();
db.ref("/activeUser").once('value').then((snapshot) => {
const user = snapshot.val();
setLoggedInUser(snapshot.val());
});
I think the call to setState inside the async code is causing this, but I can't setState elsewhere, I need it here. Does anyone have any suggestions?
It might happen that the state is been set when component is unmount. Try using useEffect as below:
const [loggedinUser, setLoggedInUser] = React.useState();
useEffect(() => {
let unmounted = false;
const [loggedinUser, setLoggedInUser] = React.useState();
db.ref("/activeUser").once('value').then((snapshot) => {
const user = snapshot.val();
!unmounted && setLoggedInUser(snapshot.val());
});
return () => { unmounted = true };
}, []);

Resources