1

I am trying to set the state of an item then use the new state as a prop which is passed to my component but it doesn't appear to be setting the state in time

constructor (props) {
    super(props)
    this.cartFirebase = firebaseApp.database().ref('carts')
    this.cartFirebase.child(DeviceInfo.getUniqueID() + '/items').push({
      item: this.props.data.name,
      qty: 1
    }).then((snap) => {
      this.state = {
        cartKey: snap.key
      }
    })
  }

Component

<AddToCartRow item={this.props.data.sizes} option='size' key={this.state.cartKey}/>
0

1 Answer 1

1

This is because at the time of rendering AddToCartRow, this.state.cartKey is null.

You're setting cartKey from within a Promise .then(..) which has not yet been fulfilled.

Your render() is actually calling before your constructor has populated this.state.cartKey.

You could write the following logic to only render the component when this.state.cartKey evaluates to true, and as we know null evaluates to false.

{this.state.cartKey && <AddToCartRow item={this.props.data.sizes} option='size' key={this.state.cartKey}/>}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.