React and firebase adding document to collection issue - Warning: Can't perform a React state update on an unmounted component - reactjs

I'm trying to add a document to a firebase collection. It works and adds the document but i get the following warning in my react console -
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 the componentWillUnmount method.
This is the utility function I wrote
export const addDocument = async (title) => {
const collectionRef = firestore.collection('collections')
const newDocRef = collectionRef.doc()
const snapshot = await newDocRef.get()
if(!snapshot.exists) {
try {
await newDocRef.set({
title,
items: []
})
} catch (e) {
console.error('Error creating document.', e.message)
}
}
}
This is the component that i'm calling the utility in and is giving me the error
const AdminPage = () => {
const handleSubmit = () => {
addDocument('hat')
}
return (
<div>
<button onClick={handleSubmit}>Add Collection</button>
</div>
)
}
All my imports and exports are fine i've just omitted it to make things more concise.

The code contains async operations so you should implement method: componentWillUnmount
As your code awaits for all async operation (get and set only I think) it should not be a case in your example. This is just a warning and according to my understanding it is showing that async operation may end when object is already destroyed.
Passing some interesting articles and questions:
one, two, three, four
if you need more there is tones of articles over the internet.
I hope it will help!

Related

Update state in setInterval via dispatch outside component

I currently have a functional component Form that triggers a task to occur. Once the submission is complete, I create a setInterval poll to poll for the status of the task. The code roughly looks like
export function Form(props: FormProps) {
const dispatch = useDispatch()
const pollTaskStatus = () => {
const intervalId = setInterval(async() => {
const response = await fetchTaskStatus() // Function in different file
if (response.status === 'COMPLETE') {
dispatch(Actions.displayTaskComplete())
clearInterval(intervalId)
}
})
}
const submitForm = async() => {
await onSubmitForm() // Function in different file
pollTaskStatus()
}
return (
...
<button onClick={submitForm}>Submit</button>
)
}
When the action is dispatched, the redux store is supposed to be updated and a component is supposed to update alongside it showing a message that the task is complete. However, I see the action logged with an updated store state but nothing occurs. If I just try to dispatch the same action with useEffect() wrapped around it outside the submitForm functions, the message appears. I've searched online and people say that you need to wrap useEffect around setInterval but I can't do that because the function that calls setInterval is not a custom hook or component. Is there a way to do this?
It's a bit difficult to answer your question without seeing all the code.
But my guts feeling is that this might no have anything to do with React.
const pollTaskStatus = () => {
const intervalId = setInterval(async() => {
console.log('fire to fetch')
const response = await fetchTaskStatus() // Function in different file
if (response.status === 'COMPLETE') {
console.log('success from fetch')
dispatch(Actions.displayTaskComplete())
}
})
}
Let's add two console lines to your code. What we want to see is to answer the following questions.
is the setInterval called in every 500ms?
is any of the call finished as success?
how many dispatch has been fired after submission
If you can answer all these questions, most likely you can figure out what went wrong.

How to call a hook function into a map in react

I'm using ketting for my React REST client.
The library provides hooks to access some data, In my case, this is this hook :
import { useResource } from 'react-ketting';
...
const { loading, error, data } = useResource('https://api.example/article/5');
I have multiples resources and I want to loop on them:
items.map(item => {
const { loading, error, data, resourceState } = useResource(item);
myItems.push({
title: data.name,
onClick: () => go(resourceState.links.get('self').href),
});
});
But React doesn't accept looping the useResource hook like this.
So I found a dirty solution that I'm not proud of...
import React from 'react';
import { useCollection, useResource } from 'react-ketting';
let myItems = [];
const Collection = ({ resource, go }) => {
const { items } = useCollection(resource);
myItems = [];
return (
<div>
{items.map(item => (
<CollectionItem go={go} resource={item} />
))}
<ElementsUser elements={myItems} />
</div>
);
};
const CollectionItem = ({ resource, go }) => {
const { data, resourceState } = useResource(resource);
myItems.push({
title: data.name,
onClick: () => go(resourceState.links.get('self').href),
});
return null;
};
Do you have any tips to deal with that problem?
And is it possible that it causes a :
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.
Using 1 component per Resource is exactly the pattern that's recommended. I'd even say it's a best practice. Note that a call to useResource will not result in an API call if there was a cached resource state.
If you find that you are seeing 1 request per iteration, you might want to make sure that your collection returns every member as an embedded resource. If you use the useCollection hook, the request will include a Prefer: transclude=item header to give a hint to the server that embedding might be desired.
Also, react-ketting will do cleanups on unmount.

How to trace sources of state changes?

I have following hook in my react app:
const MyPage = React.FC = () => {
const myContext = useContext(MyContext);
useEffect(() => {
console.log(myContext);
}, [myContext]);
}
Effect hook though fires 3 times and that's expected and works as designed. But is there way to trace source of context changes so I could remove unnecessary changes?
1st approach: Don't use an effect hook, log where you are everytime a component updates the value provided by the context
// SomeComponents.js
export default () => {
const myContext = useContext(MyContext)
<button onClick={() => {window.console.log('In SomeComponents.js, onClick handler'); myContext.incrementCount()}>
${myContext.count}
</button>
}
2nd approach
More generally, there is a tool to find how to optimize the performance of your React app. It's called the React Profiler, available since React 16.5.
Failed approach: Throw and catch an error to get the stack
useEffect(() => {
try {
throw new Error('I should be caught')
} catch (e) {
window.console.log(e)
}
}, [state])
However the state was updated, the error has the same stack, so this gives us no clue.

Best practice to prevent state update warning for unmounted component from a handler

It is a common use-case to fetch and display the data from an external API (by using XHR requests) when a certain UI component (e.g. a <button />) is clicked. However, if the component was unmounted in the meantime, the following warning appears in the console:
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 fact, the most common solution (approved by #dan-abramov) to avoid the warning seems to keep track of the mount state of the component by using the return function of useEffect to cleanup.
import React, { useState, useRef, useEffect } from "react";
import axios from "axios";
export default function PhotoList() {
const mounted = useRef(true);
const [photos, setPhotos] = useState(null);
useEffect(() => {
return () => {
mounted.current = false;
};
}, []);
function handleLoadPhotos() {
axios("https://jsonplaceholder.typicode.com/photos").then(res => {
if (mounted.current) {
setPhotos(res.data);
}
});
}
return (
<div>
<button onClick={handleLoadPhotos}>Load photos</button>
{photos && <p>Loaded {photos.length} photos</p>}
</div>
);
}
However, this seems to cause unnecessary overhead to keep track of the mounting state and to check it before every state update. This becomes especially obvious when Observables (where you can unsubscribe) instead of Promises are used.
While you indeed can unsubscribe inside of the useEffect using the cleanup function in a very neat way:
useEffect(() => {
// getPhotos() returns an observable of the photo list
const photos$ = getPhotos().subscribe(setPhotos);
return () => photos$.unsubscribe();
}, []);
The same smart cleanup is not possible within a handler:
function handleLoadPhotos() {
const photos$ = getPhotos().subscribe(setPhotos);
// how to unsubscribe on unmounting?
}
Is there a best practice to avoid the warning without the ugly manual tracking of the mounting state with useRef()? Are there good approaches for that when using Observables?
Problem is that you are trying to fetch data in your component. This is not a good idea since the component could be unmounted and you would face many possible errors.
So that, you should look for other ways.
I always do async operations in redux thunks.
You should avoid your approach. Use redux and redux-thunk if you like. If not, try to find another solution to move async operations outside of your components.
In fact, you should be writing declarative ui components which renders for given props. So that, your data should be outside of your components logic too.
That's an awesome question! This is how I would do it:
First, define a helper function (it's not cheating because it really is a highly reusable function whenever you're dealing with React and observables combined):
import * as React from 'react';
import { Observable } from 'rxjs';
export const useObservable = <Value>(
arg: () => {
observable: Observable<Value>;
value: Value;
},
) => {
const { observable, value } = React.useMemo(arg, []);
const [state, setState] = React.useState<Value>(value);
React.useEffect(() => {
const subscription = observable.subscribe(value => setState(value));
return () => subscription.unsubscribe();
}, []);
return state;
};
Just to help illustrate what this function does, the following component will display the latest value emitted by myObservable:
() => {
const value = useObservable(() => ({
observable: myObservable,
value: 'Nothing emitted yet',
}));
return <span>{value}</span>;
};
Your component will then look like this:
export default function PhotoList() {
const clicksSubject = React.useMemo(() => new Subject<undefined>(), []);
const photos = useObservable(() => ({
observable: clicksSubject.pipe(
switchMap(() => axiosApiCallReturningAnObservable()),
map(res => res.data),
),
value: null,
}));
return (
<div>
<button
onClick={() => {
clicksSubject.next(undefined);
}}
>
Load photos
</button>
{photos && <p>Loaded {photos.length} photos</p>}
</div>
);
}
When the component is dismounted, useObservable unsubs from the observable that was passed to it. This makes sure that we don't at a later point attempt to set the state, and that the data fetching API aborts (or at least gets a chance to abort) the HTTP request.

Authentication listeners when refactoring to React hooks

I'm having a little trouble figuring out how to change my authentication handling component when refactoring from a React class to React hooks.
Here's the relavant code in my class:
state = {
user: null
}
componentDidMount() {
authGetUser(user => {
if (user !== this.state.user) {
this.setState({user})
}
})
}
componentWillUnmount() {
authUnsubscribe()
}
handleAuthClick = () => {
if (this.state.user) {
authSignOut()
} else {
authSignIn()
}
}
And here it is with hooks:
const [user, setUser] = useState<firebase.User | null>(null)
useEffect(() => {
return authUnsubscribe() // runs on mount and unmount only
}, [])
useEffect(() => {
authGetUser(usr => setUser(usr))
}, [])
const handleAuthClick = () => {
if (user) {
authSignOut()
} else {
authSignIn()
}
}
Also, here are my other relevant methods:
const authGetUser = (callback: (user: firebase.User | null) => void) => {
initFirebase()
authUnsubscribe()
userUnsubscribe = firebaseAuth.onAuthStateChanged(callback)
}
export const authUnsubscribe = () => {
if (userUnsubscribe) {
userUnsubscribe()
}
}
const authSignIn = () => {
googleAuth.signIn().then((googleUser: any) => {
var credential = firebase.auth.GoogleAuthProvider.credential(googleUser.getAuthResponse().id_token)
firebaseAuth.signInAndRetrieveDataWithCredential(credential)
})
}
const authSignOut = () => {
googleAuth
.signOut()
.then(firebaseAuth.signOut())
}
Both examples work. However, when I log out and log in with the hooks version, I get an error message in console saying
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 the componentWillUnmount method.
which suggests that the cleanup is not done properly.
Yes, I know I could just continue using the version with the class which works. But I want to understand React hooks better by solving this.
Any ideas?
Wouldn't this works for you? You could use a single useEffect().
React Hooks API DOCs
useEffect(
() => {
const subscription = props.source.subscribe();
return () => {
// Clean up the subscription
setUser(null); // <--- TRY DOING SOMETHING LIKE THIS
subscription.unsubscribe();
};
},
[],
);
The clean-up function runs before the component is removed from the UI
to prevent memory leaks. Additionally, if a component renders multiple
times (as they typically do), the previous effect is cleaned up before
executing the next effect. In our example, this means a new
subscription is created on every update. To avoid firing an effect on
every update, refer to the next section.
If you want to run an effect and clean it up only once (on mount and
unmount), you can pass an empty array ([]) as a second argument. This
tells React that your effect doesn’t depend on any values from props
or state, so it never needs to re-run. This isn’t handled as a special
case — it follows directly from how the dependencies array always
works.
Generally, this happens when we have asynchronous requests and the component is unmounted before, occurring memory leak. Obviously, that this not occur in class-based components because we have componentDidMount() and componentWillUnmount() hooks, so it's more confident than useEffect() that we have manipulated the state, so I think that you need to identify the reason for the application unmount and there is the solution.
You should use one useEffect() instead two like this:
useEffect(() => {
authGetUser(usr => setUser(usr))
return authUnsubscribe() // runs on mount and unmount only
}, [])

Resources