How Do I Query current ID against ID's in a collection to show only documents with similar fields and value using react Js and Firestore- Part 2

huangapple go评论67阅读模式
英文:

How Do I Query current ID against ID's in a collection to show only documents with similar fields and value using react Js and Firestore- Part 2

问题

我的目标是获取所有包含相同值字段的文档...第一次运行我的应用程序时,它显示了集合中所有文档的所有相似值与当前ID的比较结果,以下是代码:

const [data, setData] = useState([]);
const [dataSet, setDataSet] = useState({
    regNo: "",
});

const { userId } = useParams();
let id = userId;

useEffect(() => {
    let getUserDoc = async (id) => {
        let docRef = doc(db, `dentist/${id}`);
        let docSnap = await getDoc(docRef);
        console.log('getUserDoc() received:', docSnap);
        if (docSnap.exists) {
            let theData = docSnap.data();
            console.log('getUserDoc() setting userInfo:', theData);
            setDataSet(theData);
        }
    }

    if (id) {
        getUserDoc(id);
        console.log("IdUser", id);
    } else {
        console.log('useEffect() -- no ID value');
    }
}, [id]);

let currentValue = dataSet.regNo;
console.log("currentvalue from doc", currentValue);

useEffect(() => {
    const getList = async () => {
        const collectionRef = collection(db, "dentist");
        const q = query(collectionRef, where("regNo", "==", currentValue));
        await getDocs(q).then((task) => {
            let medData = task.docs.map((doc) => ({ ...doc.data(), id: doc.id }));
            setData(medData);
            console.log("medData", medData);
        }).catch((err) => {
            console.log(err);
        });
    }
    getList();
}, []);

这个代码一开始可以正常工作,它可以比较第一个文档的regNo与集合中所有文档的regNo。但问题是,当刷新页面时,第二个useEffect 返回的 medData 是0,也就是没有文档。解决这个问题的方法是确保 currentValue 在刷新后仍然具有正确的值。为了解决这个问题,你可以将 currentValue 移到第二个 useEffect 中,确保在 getList 函数中使用正确的值。这是修改后的代码:

const [data, setData] = useState([]);
const [dataSet, setDataSet] = useState({
    regNo: "",
});

const { userId } = useParams();
let id = userId;

useEffect(() => {
    let getUserDoc = async (id) => {
        let docRef = doc(db, `dentist/${id}`);
        let docSnap = await getDoc(docRef);
        console.log('getUserDoc() received:', docSnap);
        if (docSnap.exists) {
            let theData = docSnap.data();
            console.log('getUserDoc() setting userInfo:', theData);
            setDataSet(theData);
        }
    }

    if (id) {
        getUserDoc(id);
        console.log("IdUser", id);
    } else {
        console.log('useEffect() -- no ID value');
    }
}, [id]);

useEffect(() => {
    let currentValue = dataSet.regNo;
    console.log("currentvalue from doc", currentValue);

    const getList = async () => {
        const collectionRef = collection(db, "dentist");
        const q = query(collectionRef, where("regNo", "==", currentValue));
        await getDocs(q).then((task) => {
            let medData = task.docs.map((doc) => ({ ...doc.data(), id: doc.id }));
            setData(medData);
            console.log("medData", medData);
        }).catch((err) => {
            console.log(err);
        });
    }

    if (currentValue !== "") {
        getList();
    }
}, [dataSet.regNo]);

这样修改后,currentValue 将在第二个 useEffect 中根据 dataSet.regNo 的值进行更新,确保了在刷新后仍然有正确的值。这应该解决你遇到的问题。

英文:

My goal for this was to fetch all documents that contain a field with the same value... The first time I run my application it shows all similar values from all documents in a collection against current ID, Here's the code:-

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const [data, setData] = useState([]);
const [dataSet, setDataSet] = useState({
regNo: &quot;&quot;,
});
const {userId}  = useParams();
let id = userId
useEffect(() =&gt; {
let getUserDoc = async (id) =&gt; {
let docRef = doc(db, `dentist/${id}`);
let docSnap = await getDoc(docRef);
console.log(&#39;getUserDoc() received:&#39;, docSnap);
if (docSnap.exists) {
let theData = docSnap.data();
console.log(&#39;getUserDoc() setting userInfo:&#39;, theData);
setDataSet(theData);
}
}
if (id) {
getUserDoc(id);
console.log(&quot;IdUser&quot;, id)
} else {
console.log(&#39;useEffect() -- no ID value&#39;);
}
}, [id]);
let currentValue = dataSet.regNo
console.log(&quot;currentvalue from doc&quot;, currentValue)
useEffect(()=&gt;{
const getList = async () =&gt; {
const collectionRef = collection(db, &quot;dentist&quot;)
const q = query(collectionRef, where(&quot;regNo&quot;, &quot;==&quot;, currentValue))
await getDocs(q).then((task)=&gt;{
let medData = task.docs.map((doc) =&gt; ({...doc.data(),
id: doc.id}))
setData(medData)
console.log(&quot;medData&quot;, medData)
}).catch((err) =&gt;{
console.log(err)
})
}
getList()
}, [])

<!-- end snippet -->

This worked 100%, I could compare the regNo from the first document against all the documents in the collection, Here's my console logHow Do I Query current ID against ID's in a collection to show only documents with similar fields and value using react Js and Firestore- Part 2

The challenge I'm facing now is when I refresh the page, the second useEffect returns 0 in the medData, that is, no document.. Here's my console:-
How Do I Query current ID against ID's in a collection to show only documents with similar fields and value using react Js and Firestore- Part 2

Once I refresh, the data I could see initially, disappears!

In addition, since I'm using async/await I chained everything together, at first I got all documents with similar value for regNo but when I refreshed, it all disappeared.. Here's the code:-

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

   const [data, setData] = useState([]);
const [dataSet, setDataSet] = useState({
regNo: &quot;&quot;,
});
const {userId}  = useParams();
let id = userId
let currentValue = dataSet.regNo
console.log(&quot;currentvalue from doc&quot;, currentValue)
useEffect(() =&gt; {
let getUserDoc = async (id) =&gt; {
let docRef = doc(db, `androcare/${id}`);
let docSnap = await getDoc(docRef);
console.log(&#39;getUserDoc() received:&#39;, docSnap);
if (docSnap.exists) {
let theData = docSnap.data();
console.log(&#39;getUserDoc() setting userInfo:&#39;, theData);
setDataSet(theData);
}
}
const getList = async () =&gt; {
const collectionRef = collection(db, &quot;androcare&quot;)
const q = query(collectionRef, where(&quot;regNo&quot;, &quot;==&quot;, currentValue))
await getDocs(q).then((task)=&gt;{
let medData = task.docs.map((doc) =&gt; ({...doc.data(),
id: doc.id}))
setData(medData)
console.log(&quot;medData&quot;, medData)
}).catch((err) =&gt;{
console.log(err)
})
}
if (id) {
getUserDoc(id);
console.log(&quot;IdUser&quot;, id)
getList();
} else {
console.log(&#39;useEffect() -- no ID value&#39;);
}
}, [id]);

<!-- end snippet -->

What I'm observing is upon refresh, it treats the regNo as an empty string, how I resolve this issue..

答案1

得分: 1

我不熟悉react.js,但我认为你不应该将两个查询的代码(首先是文档,然后是集合,如我在我的另一个答案中所解释的)放在两个不同的useEffect块中。

你应该按照以下方式链式连接两个查询(我让你将其集成到你的react.js代码中,在一个唯一的useEffect块中):

let id = userId;
let docRef = doc(db, `dentist/${id}`);
let docSnap = await getDoc(docRef);
if (docSnap.exists) {
  const theData = docSnap.data();
  setDataSet(theData);
  const currentValue = theData.regNo;
  const collectionRef = collection(db, "dentist");
  const q = query(collectionRef, where("regNo", "==", currentValue));
  await getDocs(q).then((task) => {
    let medData = task.docs.map((doc) => ({ ...doc.data(), id: doc.id }));
    setData(medData);
  });
}
英文:

I’m not versed in react.js but I think that you should not put the code of the two queries (first the doc then the collection, as explained in my other answer) in two different useEffect blocks.

You should chain the two queries along the following lines (I let you integrate it in your react.js code, in a unique useEffect block):

let id = userId;
let docRef = doc(db, `dentist/${id}`);
let docSnap = await getDoc(docRef);
if (docSnap.exists) {
  setDataSet(theData);
  const theData = docSnap.data();
  const currentValue = theData.regNo;
  const collectionRef = collection(db, &quot;dentist&quot;)
  const q = query(collectionRef, where(&quot;regNo&quot;, &quot;==&quot;, currentValue))
  await getDocs(q).then((task)=&gt;{
  let medData = task.docs.map((doc) =&gt; ({...doc.data(), id: doc.id}))
  setData(medData)
});

huangapple
  • 本文由 发表于 2023年6月15日 19:15:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/76481899.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定