Search code examples
javascriptreactjsreact-nativeglobal-variableslocal-variables

How to update the value of global variable react native?


I want to update the value of bjpv and finally set it's state to new updated state, which I will get from the firebase function

I am using expo for my react native application. This is a simple voting application.

class Dashboard extends React.Component {
constructor(props){
    super(props)
    this.state = ({
        name: '',
        bjp:'',
    })
    this.componentDidMount=()=>{
        var bjpv;
        console.log("var bjpv loaded")
        firebase.database().ref("candid/BJP").once('value').then(function(snapshot){
            ping = snapshot.val().votes;
            // return bjpv;
            console.log("Start firebase");
            console.log(bjpv);
            console.log(ping);
            this.setState.bjpv = this.setState.ping;
            console.log("Closing firebase")
        })
        console.log("No fire");
        console.log(bjpv);
        console.log("End message")
        this.setState(function(state, props){
            console.log("Hello")
            return {
                bjp: bjpv,
            }
        })
}
}

And I want to access my values in this const array

var data = [
    { name: 'BJP', votes : this.state.bjp, color: 'pink', legendFontColor: '#7F7F7F', legendFontSize: 10 }]

I want to finally update the value of votes in var data fetched from firebase.


Solution

  • I try to understand your code. Is this what you meant?

    class Dashboard extends React.Component {
      state = {
        name: '',
        bjp: ''
      }
    
      componentDidMount() {
        firebase.database().ref("candid/BJP").once('value')
          .then(snapshot => {
            let bjp = snapshot.val().votes;
            this.setState({ bjp });
          })
      }
    }