我已经阅读了几个SO Q& A(如In Firebase when using push() How do I get the unique ID and store in my database),但无法使我的代码正常工作。
firebase.push
之后,获取创建的密钥并读取push
调用中写入的数据。
addCard = async ({
number, expMonth, expYear, cvc,
}) => {
this.setState({ addingCardInProcess: true });
try {
const tokenObject = await stripe.createTokenWithCard({
number, expMonth, expYear, cvc
});
firebase
.database()
.ref(`/stripe_customers/${uid()}/sources`)
.push({ token: tokenObject.tokenId })
.then(() => {
// I want to get the key and read the pushed data here.
// How do I do it?
this.setState({ addingCardInProcess: false });
this.cardAlert(true);
})
.catch((err) => {
this.setState({ addingCardInProcess: false });
this.cardAlert(false, err.message);
});
} catch(err) {
this.cardAlert(false, err.message);
this.setState({ addingCardInProcess: false })
}
};
答案 0 :(得分:1)
addCard = async ({
number, expMonth, expYear, cvc,
}) => {
this.setState({ addingCardInProcess: true });
try {
const tokenObject = await stripe.createTokenWithCard({
number, expMonth, expYear, cvc
});
let id = firebase.database().ref().push().key;
let body = { token: tokenObject.tokenId };
firebase
.database()
.ref(`/stripe_customers/${uid()}/sources`).child(id)
.set(body)
.then(() => {
// I want to get the key and read the pushed data here.
// Now you have your key here in "id" variable and data in "body" variable
this.setState({ addingCardInProcess: false });
this.cardAlert(true);
})
.catch((err) => {
this.setState({ addingCardInProcess: false });
this.cardAlert(false, err.message);
});
} catch(err) {
this.cardAlert(false, err.message);
this.setState({ addingCardInProcess: false })
}
};
现在你有'id'变量中的自动生成键和'body'变量中的推送数据。
希望它有所帮助!