Javascript 如何防止firebase记录中的重复

Javascript 如何防止firebase记录中的重复,javascript,firebase,react-native,firebase-realtime-database,Javascript,Firebase,React Native,Firebase Realtime Database,我正在构建一个电子商务应用程序,我正在尝试将用户按下添加到购物车中的每一项(调用functionsCombined()函数)都保存在firebase中,但我不希望记录重复 this.state = { added: false, duplicate: false, } componentWillMount() { //gets the data in firebase this.props.fetchData(); } functionsCombined(re

我正在构建一个电子商务应用程序,我正在尝试将用户按下添加到购物车中的每一项(调用functionsCombined()函数)都保存在firebase中,但我不希望记录重复

this.state = {
    added: false,
    duplicate: false,
}

componentWillMount() {
    //gets the data in firebase
    this.props.fetchData();
}

functionsCombined(recipe) {
    //the user pressed add to cart
    //recipe is the item to be added
    if (this.state.added) {

    } else {
        this.functionZero(recipe);
        this.functionOne();
        this.functionTwo(recipe);
    }
}

functionZero(recipe) {
    //this.props.check is the data we pulled from firebase
    //to check if the firebase records is the same as the one here
    /but even when that's true, setState doesn't work for some reason
    this.props.check.map((one) => {
        if (one.id === recipe.id) {
            this.setState({
                duplicate: true
            })
        } else {

        }
    })
}


functionOne() {
    this.setState({
        added: true
    })
}

functionTwo(recipe) {
    if (this.state.duplicate === false) {
        const {
            currentUser
        } = firebase.auth();
        firebase.database().ref(`/users/${currentUser.uid}/recipes`)
            .push(recipe);
    } else {

    }
}

在保存到firebase之前,可以使用通用唯一标识符(UUID)。 像这样的

const uuidv4=require('uuid/v4')


这将为您保存的每个firebase记录生成唯一的id

这不是必需的,因为firebase具有内置于push()或.childByAutoId(Swift)的功能-它将在创建节点时生成唯一的密钥。但从概念上讲,这是正确的。
..... 
firebase.database().ref(`/users/${currentUser.uid}/recipes`+uuidv4())
            .push(recipe);

.....