Firebase,React CRUD:按文档ID删除文档

时间:2020-10-14 09:52:35

标签: reactjs firebase google-cloud-firestore

我的组件UniqueVenueListing显示现场音乐表演(演出)的列表。
通过GigRegister组件中的axios请求引入了演出的完整列表,并将其作为props传递给UniqueVenueListing,在那里它们被映射并呈现给浏览器。 我想添加删除功能,以便已登录的用户可以删除特定演出。
到目前为止,这是我做的事情:在UniqueVenueListing中,我希望实时订阅数据库更改,因此我包含以下请求:

const ref = firebase.firestore().collection('gig-listing')

const getGigs = () => {
    ref.onSnapshot(querySnapshot => {
        const items = []
        querySnapshot.forEach(doc => {
            items.push(doc.data())
        })
        setGigs(items)
    })
}

然后我写了一个函数来执行删除-

const deleteGig = () => {
    ref
    .doc(//some variable representing the specific doc id of a gig)
    .delete()
    .catch(err => {
        console.error(err)
    })
}

最后,我有一个指向此删除功能的按钮:

const button = <StyledButton onClick = {()=> {deleteGig(//some passed in gig)}}>Delete Gig</StyledButton>

所以我拥有所有的“位”,我只是不知道如何将它们全部绑在一起以产生删除。我希望能够基于演出ID删除演出,我知道可以从getGigs函数中检索该演出-console.log(doc.id)产生ID)。这是整个组件:

import React, {useState, useEffect} from 'react'
import Giglisting from './Giglisting'
import Button from "@material-ui/core/Button";
import { withStyles } from '@material-ui/core/styles';
import firebase from 'firebase'

const StyledButton = withStyles({
    root: {
      background: '#54ADA6',
      borderRadius: 3,
      border: 0,
      color: 'black',
      height: 30,
      padding: '0 30px',
      marginRight: '1px'
      
    },
    label: {
      textTransform: 'capitalize',
    },
  })(Button);


const UniqueVenueListing = (props) => {
const gigList = props.gigList
const [gigs, setGigs] =useState([])


const ref = firebase.firestore().collection('gig-listing')

const getGigs = () => {
    ref.onSnapshot(querySnapshot => {
        const items = []
        querySnapshot.forEach(doc => {
            items.push(doc.data())
        })
        setGigs(items)
    })
}

useEffect(() => {
    getGigs()
},[])

const deleteGig = () => {
    ref
    .doc(gigs.id)
    .delete()
    .catch(err => {
        console.error(err)
    })
}

const button = <StyledButton>Delete Gig</StyledButton>

    return(
        <div>
          {
              gigList.map(gigs => {
                 return <Giglisting
                 gigtitle = {gigs.name}
                  genre = {gigs.genre}
                  time = {gigs.time}
                  buytickets = {gigs.tickets}
                  button = {button}
                  />
              })
            }
        </div>
    )
}

export default UniqueVenueListing

这是GigRegister组件的一部分,用于过滤并将数据发送到UniqueVenueListing

      authListener() {
        auth().onAuthStateChanged((user) => {
          if (user) {
            this.setState(
              {
                userDetails: user
              },
              () =>
                axios
                  .get(
                    "https://us-central1-gig-fort.cloudfunctions.net/api/getGigListings"
                  )
                  .then((res) => {
                    let filteredGigs = res.data.filter((gig) => {
                      return gig.user === this.state.userDetails.uid;
                    });
                    this.setState({
                      filterGigs: filteredGigs
                    });
                  })
            );
          } else {
            this.setState({
              userDetails: null,
            });
            console.log("no user signed in");
          }
        });
      }

      componentDidMount() {
        this.authListener();
      }

1 个答案:

答案 0 :(得分:1)

问题始于您的''函数,您在其中提取每个文档的数据,但忽略了以后需要的文档ID。您将需要更改该功能以获取每个文档的数据和ID:

const getGigs = () => {
    ref.onSnapshot(querySnapshot => {
        const items = []
        querySnapshot.forEach(doc => {
            items.push({ id: doc.id, data: doc.data() })
        })
        setGigs(items)
    })
}

然后,您可以在渲染方法中同时渲染数据 ID,然后将ID传递给deleteGig