简体   繁体   中英

Get data of a field from a collection using a selected document in Firestore and React

I am looking to display the data in a field. At this time, my database structure is represented in Firestore like the following: Collection (lunch) => document (mon, tue, web, thu, fri) => field (dessert, main, side, soup)

Firestore database structure

What I am trying to do here is get all the documents from the collection and retrieve it by mapping. The expected result is to return one value in a selected field. For example, I want to display dessert of tue. The result should display "Banana & Coconut Tapioca Pudding". However, it returned to all the data locating on the field. Like the illustrating image below.

Outcome

Here is the code snippet I tried using but it did not work:

export default function Menu() {
const [menu, setMenu] = useState([]);    
useEffect(() => {
    fetchMenu();            
}, []);

useEffect(() => {
    console.log(menu)
}, [menu]);

function fetchMenu() {
    const menuCollection = collection(db, 'lunch')
    getDocs(menuCollection)
    // .then((doc)=>{console.log(doc.data(),doc.id)})
        .then(response => {
            const menuRef = response.docs.map((doc) =>(
                {
                    data:doc.data(),
                    id: doc.id
                }
            ))
            setMenu(menuRef)
            })
        .catch(error => console.log(error.message))
}

return (
    <>
        <SubNav content="Menu"></SubNav>

        <div className="App">
        <ul>
            {menu.map((menu) => (
                <li key={menu.tue}>{menu.data.dessert}</li>
            ))}
        </ul>
            
        </div>
    </>
);

Thank you!

As per your image you your menu looks like

[
 {data: {...}, id: 'mon'},
 {data: {...}, id: 'tue'},
 {data: {...}, id: 'wed'},
]

So while iterating on this array menu.tue won't work you would have to do a if check like this

<ul>
      {menu.map((menu) => (menu.id === 'tue' && 
           <li key={menu.tue}>{menu.data.dessert}</li>
      ))}
</ul>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM