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}/>
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}/>}