Search code examples
javascriptreactjsgoogle-cloud-firestorereturnes6-promise

How to get data from cloud firestore then filter it, map it then return it?


I am trying to get data from the firestore and then filter it then map it like so:

return Inventory
.filter(x =>x["sub_category"] === item && x["category"] === category)
.map(({id, item, price, quantity, image})=>{

//sets the default value for the item with that specific id
const defVal = parseInt((selectedQty.id === id)?selectedQty.qty:0)

return (
    <React.Fragment key={uuid()}>
        <div className="card">
            <img src={image()} alt={item} />
            <p>{item}</p>
            
            <div className="innerBox">
                <div className="dropdown">
                    <label htmlFor="quantity">Qty:</label>
                    <select id="quantity" defaultValue={defVal===0?1:defVal} onChange={e => {
                        e.preventDefault()
                        setSelectedQty({id, qty: parseInt(e.target.value)})
                    }}>
                    {
                        Array(quantity).fill().map((_, i)=> {
                            if(i===0){
                                return <option key={uuid()} value={0}>-</option>
                            }else{
                                return <option key={uuid()} value={i} >{i}</option>
                            }
                        })
                    }
                    </select>
                </div>
                <b>$ {price}</b>
            </div>
            <button type="submit" onClick={()=> {
                addToCart(id, item, parseInt(finalQty), price, image(), parseInt(finalQty)*parseFloat(price))
                setSelectedQty({id:null, qty: 0})
            }}>Add to Cart</button>
        </div>
    </React.Fragment>
)})

Currently I am using Inventory Array but I want to switch to firestore but I have no clue how to do it. I am aware of the step db.collection().get().then(etc...) but i don't know how to map it to return it inside the Then


Solution

  • When you fetch data from cloud firestore, it returns a document / collection snapshot.

    Document:

    db.collection("colName").doc("docID").get().then(docSnapShot=>{
        const docID = docSnapShot.id;
        const docData = docSnapShot.data();
    })
    

    Collection:

    db.collection("colName").get().then(colSnapShot=>{
        const isEmpty = colSnapShot.empty;
        const docsData = colSnapShot.docs.forEach(docSnapShot=>{
            return docSnapShot.data();
        })
    })
    

    I believe your solution will look something like this:

    let arrOfDocs = await db.collection("colName").get().then(colSnapShot=>{
        return colSnapShot.docs.map(docSnapShot=>{
            return docSnapShot.data();
        })
    })
    

    Note that to listen to live updates, replace get().then(snapshot=>{}) with onSnapshot(snapshot=>{})