【问题标题】:Reading the created key and data after firebase.push()在 firebase.push() 之后读取创建的密钥和数据
【发布时间】:2018-11-26 10:19:16
【问题描述】:

我的问题

我已经阅读了几个关于此的 SO Q&A(如 In Firebase when using push() How do I get the unique ID and store in my database),但无法使我的代码正常工作。

我想做什么

在firebase.push之后,获取创建的key,读取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 })
    }
  };

【问题讨论】:

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


    【解决方案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”变量中拥有推送的数据。

    希望对你有帮助!

    【讨论】:

      猜你喜欢
      • 2016-12-05
      • 1970-01-01
      • 1970-01-01
      • 2013-07-14
      • 1970-01-01
      • 2018-01-02
      • 1970-01-01
      • 2020-04-15
      • 1970-01-01
      相关资源
      最近更新 更多