React - uncaught TypeError: Cannot read property 'setState' of undefined
This is due to this.delta
not being bound to this
.
In order to bind set this.delta = this.delta.bind(this)
in the constructor:
constructor(props) {
super(props);
this.state = {
count : 1
};
this.delta = this.delta.bind(this);
}
Currently, you are calling bind. But bind returns a bound function. You need to set the function to its bound value. TypeError: Cannot read properties of undefined (reading 'setState')
If you declare your function in the following manner
setEmailVal = val => {
this.setState({email: val.currentTarget.value});
}
It works fine.If you wish to do it in the other (old, if I am not wrong) way, then you'd need to bind the function to the class for the subcomponent, i.e. the onChange handler in the class to "see" it:
constructor(props) {
super(props);
this.state = {email: ""};
this.setEmailVal = this.setEmailVal.bind(this);
}
Lastly, you could do a direct bind inside the return component itself return (
<input type="text" onChange={this.setEmailVal.bind(this)} value={this.state.email} />
);
React - TypeError: Cannot read property 'setState' of undefined
You need to bind updateTime
constructor(props) {
...
this.updateTime = this.updateTime.bind(this)
}
or use arrow functionupdateTime = () => {
//updating the time by set state
this.setState( (state,props) => {date:new Date()} );
}
and change your setState to this.setState({
date: new Date()
});
or this.setState( (state,props) => ({date:new Date()}) );
TypeError: Cannot read property 'setState' of undefined react
navigator.geolocation.getCurrentPosition(function (position) {
this.setState({
lat: position.coords.latitude,
lng: position.coords.longitude,
});
});
React doesn't understand this
in here because its referring to the function scope, not React scope. You can change the syntax to fat arrow function, which using lexical scoping/thisnavigator.geolocation.getCurrentPosition( (position) => {
this.setState({
lat: position.coords.latitude,
lng: position.coords.longitude,
});
});
How to fix Cannot read property 'setState' of undefined in React
You lost context here since anon. function used:
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'
});
Use arrow function lilke this:ref.once("value").then((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'
});
Cannot read property 'setState' of undefined in ReactJs
Try initializing your state inside a constructor and bind the function like below
constructor(props) {
super(props);
this.state = {
alpha: ""
};
this.handleChange = this.handleChange.bind(this);
}
handleChange(e) {
this.setState({
alpha: e.target.value
});
}
React Cannot read property 'setState' of undefined in if-block
In your getFilteredTrades
and getAllTrades
functions this
refers to the functions itself and not the object and those functions don't have a member setState
.
You can resolve the problem in two ways:
- Declaring them as arrow functions which does not bind
this
by writinggetFilteredTrades = () => { ... }
andgetAllTrades = () => { ... }
. - Bind the
this
keyword of the functions to the class object by writingthis.getFilteredTrades = this.getFilteredTrades.bind(this)
andthis.getAllTrades = this.getAllTrades.bind(this)
in your constructor.
React - TypeError: Cannot read property 'setState' of undefined (Arrow functions)
Should use like this:
import React from 'react';
function App() {
const [reader, setReader] = React.useState(0);
const FormComp = () => {
//rest of the code
return <div>Clicked {reader} times</div>
};
const Ques1 = () => {
return (
<button onClick={() => setReader(reader+1)}>Increase</button>
)
};
return (
<div className="App">
<FormComp />
<Ques1 />
</div>
);
}
export default App;
You can set whatever value you want in setReader function. Get Error 'Cannot read property 'setState' of undefined' on setState line
I get your question.
I think this will be ok.
import React from 'react';
export default class Dashboard extends React.Component {
constructor(props) {
super(props);
this.state = {dataArray: []};
}
async componentDidMount() {
console.log("i am inside dashboard");
//console.log(this.props.user);
//console.log(this.props.database);
let database = this.props.database;
const docRef = database.collection("Some_Collection_here").doc("Some_Id_here")
let dataRetrieved = null;
docRef.get().then(doc => {
if (doc.exists) {
const dataRetrieved = doc.data();
this.setState ({dataArray: dataRetrieved});
} else {
console.log("Error: no such document exists");
}
})
}
render() {
return (
<div>
</div>
);
}
}
The reason is:- This context
- Lexical scope
Related Topics
Angularjs - UI Router - Programmatically Add States
How to Subscribe to Topics with Web Browser Using Firebase Cloud Messaging
Get Unique Results from JSON Array Using Jquery
Differencebetween JavaScript and Ecmascript
How to Create a Stopwatch Using JavaScript
How to Pass Jsf Managed Bean Properties to a JavaScript Function
Rest with Express.Js Nested Router
JavaScript .Replace Only Replaces First Match
Prototyping Object in JavaScript Breaks Jquery
Validating User's Utf-8 Name in JavaScript
Unexpected Token Illegal in Webkit
Ecmascript 2015: Const in for Loops
Converting a Buffer into a Readablestream in Node.Js
Remove Zero-Width Space Characters from a JavaScript String
Why and When to Use Default Export Over Named Exports in Es6 Modules
What Causes the Error "Can't Execute Code from a Freed Script"
Alternative or Polyfill for Array.From on the Internet Explorer