Ad

How To Use SetState Or Function With Firebase

this is my code from a React Project with firebase , I am stuck from the Morning in this Problem please help me plzzz

constructor (){
        super()
        this.state = {Message : false}
        this.Navigate = this.Navigate.bind(this)


        CompLoad = true

        var i = firebase.auth().currentUser.uid

        firebase.database().ref('users/' + i + '/inbox').limitToLast(1)

         .on('value' , function (x){

            if (CompLoad === false){

            var data = x.val()  

            alert(JSON.stringify(data))

            R = 'Inbox'

            this.Navigate()

            }

            if (CompLoad === true){
                CompLoad = false
            }


            })

            }

it gives me error :-

TypeError: Cannot read property 'Navigate' of null

Navigate function

Navigate =  () => {     
        this.context.router.history.push('/' + R)
    }

if i replace Navigate with setState

this.setState({
                Message : true
            })

react says :

TypeError: Cannot read property 'setState' of null
Ad

Answer

Your callback function is changing the context of this and its no longer the class.
Either use an arrow function to get a lexical context:

 .on('value' , (x) => {
....

Or temporarily hold the this value above the callback and use it:

// outside the callback in the constructor
const that = this;
// inside the callback
 .on('value' , function (x){
that.Navigate()
Ad
source: stackoverflow.com
Ad