[英]How to get a single doc info from firebase?
function AccountPage() {
const [{ patients, user }, dispatch] = useStateValue();
var therapist = '';
db.collection('therapists').doc(user.uid).get().then((snapshot) => {
therapist = snapshot.data()
console.log(therapist)
})
useEffect(() => {
console.log(therapist)
var allService = therapist.service.service[0].label
for (let i = 1; i < therapist.service.service.length; i++) {
allService += ', ' + therapist.service.service[i].label;
}
var allLanguages = therapist.language.language[0].label
for (let i = 1; i < therapist.language.language.length; i++) {
allLanguages += ', ' + therapist.language.language[i].label;
}
}, [])
I'm trying to read a document in the firebase collection.我正在尝试阅读 firebase 集合中的文档。 I can read it and display to console, but for some reason I am not able to save the data.
我可以读取它并显示到控制台,但由于某种原因我无法保存数据。 If I try to use therapist variable later in the code, it is undefined.
如果我稍后在代码中尝试使用治疗师变量,它是未定义的。 I tried using useState, but it does the same thing, where therapist is undefined.
我尝试使用 useState,但它做同样的事情,其中治疗师未定义。 I really don't get it.
我真的不明白。
Tried using useState, with or without therapist in UseEffect, without useEffect尝试使用 useState,在 UseEffect 中有或没有治疗师,没有 useEffect
Something to keep in mind with React components is that their render methods are to be considered pure, synchronous functions. React 组件要记住的一点是,它们的渲染方法被认为是纯同步函数。 The entire body of a React function component is the render "method".
React function 组件的整个主体是渲染“方法”。 Each time
AccountPage
is rendered is declares therapist = ""
, and then an unintentional side-effect to collect the firebase document is kicked off.每次呈现
AccountPage
时都声明therapist = ""
,然后开始收集 firebase 文档的无意副作用。 The useEffect
hook runs after the component has rendered and tries to read properties of the empty string value that is therapist
and throws the error. useEffect
挂钩在组件呈现后运行,并尝试读取空字符串值的属性,即therapist
并抛出错误。
therapist
should be part of the React state so that it can be updated and trigger a rerender with the fetched data. therapist
应该是 React state 的一部分,以便它可以更新并使用获取的数据触发重新渲染。 The firebase document should be fetched as an intentional side-effect via a useEffect
hook. firebase 文档应该通过
useEffect
挂钩作为有意的副作用获取。
function AccountPage() {
const [{ patients, user }, dispatch] = useStateValue();
const [therapist, setTherapist] = React.useState();
// Fetch therapists document for specific user
useEffect(() => {
if (user.uid) {
db.collection('therapists').doc(user.uid).get()
.then((snapshot) => {
setTherapist(snapshot.data());
});
}
}, [user]);
// Compute services and languages when therapist state updates
useEffect(() => {
console.log(therapist);
const allService = therapist?.service?.service
.map(({ label }) => label)
.join(", ");
const allLanguages = therapist?.language?.language
.map(({ label }) => label)
.join(", ");
...
}, [therapist]);
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.