Sachin Titus
Sachin Titus

Reputation: 2339

Firestore async call inside useEffect() function causes error when navigating around routes

Async function for fetching an image from Firestore Storage causes an error when I navigate to another route and comeback. Here is the useEffect method in Items component

const Item = (props) => {
const [itemImage, setItemImage] = useState('')
const [isEditing, setIsEditing] = useState('')
const [isDeleting, setIsDeleting] = useState(false)

useEffect(()=>{
    setItemImage(placeholder)  
    if(props.itemImage){
        firestoreService.getImageUrl(props.itemImage, 'itemImage')
            .then(url => {
                
                setItemImage(url)
            })
            .catch(err => {
                console.log("error")
            })
    }      
},[])

The component called Item gets rendered only in /items route. When I go back to / route and come back to /items route, I get the following error. How can I fix it?

Warning: Can't perform a react state update on an unmounted component error

Upvotes: 0

Views: 34

Answers (1)

Mohammad Faisal
Mohammad Faisal

Reputation: 2363

When you are trying to setState on an unMounted Component you get this error message.

Here in your example

firestoreService.getImageUrl(props.itemImage, 'itemImage')
            .then(url => {
                setItemImage(url)
            })
            .catch(err => {
                console.log("error")
            })    

you are calling a function that will take some time to return. meanwhile if you go back to another component/route your current component becomes unmounted but when you get the return from firebase it tries to update the state in setItemImage(url)

thats why you are getting this error.

Upvotes: 1

Related Questions