My app retrieve data from Firebase Realtime database and trying to load it in 'state' but get error 'Cannot read property setState
of undefined'.
I tried to add bind in constructor but it doesn't work
import React from 'react';
import { View } from '@vkontakte/vkui';
import * as firebase from "firebase/app";
import {config} from './dbinit' // import firebase config
import "firebase/database";
import Home from './panels/Home';
class App extends React.Component {
constructor(props) {
super(props);
this.setState = this.setState.bind(this);
this.state = {
activePanel: 'home',
db: null,
loading: true,
};
console.log("init");
}
componentDidMount = () => {
let ref = firebase
.initializeApp(config)
.database()
.ref();
ref.once("value").then(function onSuccess(res) {
console.log("success", res.val())
this.setState({db: res.val(), loading: false})
// ERROR GOES HERE 'Unhandled Rejection (TypeError): Cannot read property 'setState' of undefined'
});
}
go = (e) => {
this.setState({activePanel: e.currentTarget.dataset.to})
};
render() {
const { loading, db } = this.state;
return loading ? (
<div>loading...</div>
) : (
<View activePanel={this.state.activePanel}>
<div>loaded</div>
</View>
);
}
}
export default App;
I expect correct work of setState
but actual have error Cannot read property 'setState' of undefined'