Reputation: 3
I am getting the following error after compiling in the console
Uncaught TypeError: Cannot read property 'setState' of undefined
this is my code please can u help me to find the mistake ? i wanna save the data of childData.pic on x then i read it on i tried this.x , this.state.x , x ... and every time i get the same error
import React, { Component } from 'react'
import * as firebase from 'firebase'
import './scss/style.scss';
import QuickView from './QuickView';
export default class Dashboard extends Component {
constructor() {
super();
this.state = {
speed: '', snapshot: undefined, x: ''
}
}
componentDidMount() {
var w = firebase.auth().currentUser
var rootRef = firebase.database().ref(`restaus/`).orderByKey();
rootRef.once("value")
.then(function (snapshot) {
snapshot.forEach(function (childSnapshot) {
var key = childSnapshot.key;
var childData = childSnapshot.val();
var x;
this.setState({
x: childData.pic,
})
});
});
this.setState({
email: w.email,
})
}
render() {
return (
<div>
<h4>your email is {this.state.email}</h4>
<div className="product">
<div className="product-image">
<img src={this.x} /*onClick={this.quickView.bind(this, name)}*/ />
</div>
<h4 className="product-name">{this.state.x}</h4>
<p className="product-price">{this.props.x}</p>
<div className="product-action">
<button type="button" >Add To cart</button>
</div>
</div>
</div>)
}
}
Upvotes: 0
Views: 864
Reputation: 686
Please format your code properly, it is hard for people to follow. The problem is you use function(snapshot)
, in this case this
not point to your Component, it point to function which call it.
You can use arrow function to void this issue https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions
For example:
rootRef.once("value").then((snapshot) => {
snapshot.forEach((childSnapshot) => {
...
this.setState(...)
})
})
Upvotes: 3