I'm pulling data from a firebase collection cafes
into a React component called CafeReviews
, and then setting that data into a state variable called cafe
.
The data coming back has the following shape:
{
name: cafe name,
photoURL: photo url
}
The strange behavior is that sometimes the data renders to the browser, but other times the browser crashes and gives the following error:
TypeError: cafe.data() is not a function
I'm assuming this is an async error - that the browser is loading the component before the state has been set. So how do I set state within a .then
block, that itself is within the useEffect
hook?
Here's the component in full:
import React, { useState,useEffect } from 'react'
import db from '../fbConfig'
const CafeReviews = ({match}) => {
const [cafe,setCafe] = useState([])
let id = match.params.id
useEffect(() => {
db.collection('cafes')
.doc(id)
.get()
.then(snapshot => {
setCafe(snapshot)
})
},[])
return(
<div>
<h1>{cafe.data().name}</h1>
</div>
)
}
export default CafeReviews
question from:
https://stackoverflow.com/questions/65930067/strange-set-state-behaviour-inside-then-block 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…