Search code examples
javascriptreactjsreact-nativeasync-awaitasynchronous-javascript

Async Await with SetState... am I doing this right?


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: '[email protected]',
        },
      }
      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>
    )
  }
}

Solution

  • 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: '[email protected]',
            },
          }
          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>
        )
      }
    }