-1

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.

Yossi
  • 5,577
  • 7
  • 41
  • 76
Shrikant Jha
  • 73
  • 11

1 Answers1

0

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 });
      })
  }
}
roel
  • 1,640
  • 14
  • 13
  • Thank you so much @roel. The code is working now. One more thing can you explain me where I was doing wrong? – Shrikant Jha May 06 '19 at 09:40
  • This line: `this.setState.bjpv = this.setState.ping`. I think you meant `this.state.bjpv = this.state.ping` because `setState` is a function, but that doesn't work either. You can't directly change the state variable, you must use `setState` to change state variable. – roel May 06 '19 at 13:11