0

How to write the variable s in state? How to write a variable in state as the key that contains snap.key from the database?

componentDidMount(){ 

    let cardQuantity = firebase.database().ref("Users"); 

    cardQuantity.on('child_added',snap => { 

        let cardsValue = cardQuantity.child(snap.key); 

        let cardId = {cardId : snap.key}; 
        this.setState({cardsId : [cardId].concat(this.state.cardsId)}); 

        let s = snap.key;
        this.setState({cards : []}); 

        cardsValue.on('value',snap => { 

            snap.forEach((childSnapshot)=> { 
                let card = {text: childSnapshot.val(), id: childSnapshot.key}; 
                //   this.setState({s : [card].concat(this.state.cards)}); 
            });
        }); 
    }) 
}

<div className="Info" > 
    { this.state.cardsId.map( cardsId => <div className="Cards" key={cardsId.cardId}> 
    //    {this.state.cards.map( card => <h2 key={card.id} >
    {card.text}</h2>) } 
</div>) }
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807

1 Answers1

2

You can do a bracket notation of the key: {[key]: value}

this.setState({[s] : [card].concat(this.state.cards)});  

You can read more about this here.

Daniel Andrei
  • 2,654
  • 15
  • 16