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
Related Questions
- → Import statement and Babel
- → should I choose reactjs+f7 or f7+vue.js?
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → .tsx webpack compile fails: Unexpected token <
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → React Native with visual studio 2015 IDE
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
- → How do I determine if a new ReactJS session and/or Browser session has started?
- → Alt @decorators in React-Native
- → How to dynamically add class to parent div of focused input field?
Ad