Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
159 views
in Technique[技术] by (71.8m points)

javascript - Strange set state behaviour inside .then block

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your initial state for cafe is [], so when you call cafe.data() on that, it gives the error you get. You need to make sure that your rendering code handles both the initial state and the data from the database, typically by ensuring they have the same shape.

For example:

const [cafe,setCafe] = useState({ name: "loading..." })

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...