0

I'm trying to make the user Add a Card if it doesn't have one saved and if the user adds one, disable the button and tell it that I'll be using the saved one.

The way of getting the token via tipsi-stripe is via await. Am I doing something wrong? Maybe I don't understand the concept completely?

export default class NewCardPage extends Component {
  constructor(props){
    super(props)
    this.state = {
      gotToken: false,
    };
  }

  render() {
    async function paymentRequestWithCardForm() {
      const options = {
        prefilledInformation: {
            email: 'jane.doe@outlook.com',
        },
      }
      try {
        const token = await stripe.paymentRequestWithCardForm(options)
        if (token){this.setState({ gotToken:true });} 
        else {this.setState({ gotToken:false });}
      }
      catch(err) {
        console.log(err.code)
        {this.setState({ gotToken:false });}
      }
    }

    return(
    <View style={styles.buttonContainer}>
      {this.state.gotToken === false ? <Button title='Add a Credit Card' style={styles.buttonStyle} onPress={() => { paymentRequestWithCardForm() }}></Button> : <Button disabled={true} title='Using saved credit card' style={styles.buttonStyle}></Button> }
    </View>
    )
  }
}
  • 4
    Not a good idea to have `paymentRequestWithCardForm` in `render` – Taki Feb 21 '20 at 16:06
  • Although you should bind the callback to your component instance this should still work at first sight. Is there any error happening? How does the behaviour differ from the desired behaviour? Any error messages ? – trixn Feb 21 '20 at 16:09
  • @Taki I moved it outside the render. took out the word function out and edited `paymentRequestWithCardForm` for `this.paymentRequestWithCardForm ` @trixn i think it was was Taki mentioned. might the order, I also though I was doing the correct thing. – christopher de jesus Feb 21 '20 at 16:15

1 Answers1

1

That's a common pattern, however it's more efficient to define the function as a class property (so that it's not created every render):

export default class NewCardPage extends Component {
  state = {
      gotToken: false,
    }

  paymentRequestWithCardForm = aync() => {
      const options = {
        prefilledInformation: {
            email: 'jane.doe@outlook.com',
        },
      }
      try {
        const token = await stripe.paymentRequestWithCardForm(options)
        if (token){this.setState({ gotToken:true });} 
        else {this.setState({ gotToken:false });}
      }
      catch(err) {
        console.log(err.code)
        {this.setState({ gotToken:false });}
      }
    }

  render() {

    return(
    <View style={styles.buttonContainer}>
      {this.state.gotToken === false ? <Button title='Add a Credit Card' style={styles.buttonStyle} onPress={this.paymentRequestWithCardForm}></Button> : <Button disabled={true} title='Using saved credit card' style={styles.buttonStyle}></Button> }
    </View>
    )
  }
}
Gerard
  • 618
  • 5
  • 18