简体   繁体   中英

How to use key generated by firebase database push method in write operation?

I am using react, redux and along with firebase. I have my action like below:

export function addPost(postData) {
    firebase.database().ref('posts').push().update({
        title: postData.title,
        text: postData.text,
        userId: firebase.auth().currentUser.uid,
        postid: ?????????
    })
    return {type: "ADD_POST", payload: postData}
}

I am suppose to create in firebase database something like this:

LY7iT1sgmJvjCmBh1GZ: {
    title: some title,
    text: some text,
    postid: LY7iT1sgmJvjCmBh1GZ
}

LY7iT1sgmJvjCmBh1GZ is unique key generated by push method. I want to my postId property be the same - how to achieve this ?

push() returns a Reference whose key property is the randomly generated key on the client:

const ref = firebase.database().ref('posts').push();
const key = ref.key;

Then you can use that in your data:

ref.set({
    ...
    postid: key
});

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