在firebase.push()之后读取创建的键和数据

时间:2018-06-17 07:53:58

标签: javascript firebase react-native firebase-realtime-database

我的问题

我已经阅读了几个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 })
    }
  };

1 个答案:

答案 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'变量中的推送数据。

希望它有所帮助!