Yossi
Yossi

Reputation: 6027

Reading the created key and data after firebase.push()

My problem

I have read several SO Q&A on this (like In Firebase when using push() How do I get the unique ID and store in my database) but cannot make my code to work.

What I am trying to do

After firebase.push, to get the created key and read the data written in the push call.

Here is the code:

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 })
    }
  };

Upvotes: 1

Views: 121

Answers (1)

mark922
mark922

Reputation: 1167

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 })
}
};

Now you have the auto generated key in 'id' variable and your pushed data in 'body' variable.

Hope it helps!

Upvotes: 1

Related Questions