when I try to handle the API response. I suspect it's something wrong with this binding but I can't figure out how to fix it. Here's the code of my component: React recommends bind this in all methods that needs to use this of class instead this of self function. I don't know the size of your project but I personally advise against using the current state of the component to manipulate datas. You should use external state like Redux or Flux or something else for that.
Make sure you use arrow functions to correctly bind 'this'
handlePageChange = (page) => {
this.setState({
currentPage: page
});
}
This will give you 'this.setstate is not a function'
handlePageChange(page) {
this.setState({
currentPage: page
});
}
The callback is made in a different context. You need to bind
to this
in order to have access inside the callback:
VK.api('users.get', {
fields: 'photo_50'
}, function(data) {
if (data.response) {
this.setState({ //the error happens here
FirstName: data.response[0].first_name
});
console.info(this.state.FirstName);
}
}.bind(this));
EDIT:
Looks like you have to bind both the init
and api
calls:
VK.init(function() {
console.info("API initialisation successful");
VK.api('users.get', {
fields: 'photo_50'
}, function(data) {
if (data.response) {
this.setState({ //the error happens here
FirstName: data.response[0].first_name
});
console.info(this.state.FirstName);
}
}.bind(this));
}.bind(this), function() {
console.info("API initialisation failed");
}, '5.34');
But when you try to run the component above, you will get the this.setState is not a function error: Learn how to fix this.setState is not a function error in your React application Then again, you may want to consider using a function instead of a class for declaring a React component. Since the release of React hooks in 2018, function component syntax is the recommended way to create React components. But the downside of this way is that you need to bind each function that needs to use this.setState() function in the constructor.
TypeError: this.setState is not a
function
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
}
handleClick() {
this.setState({ count: this.state.count + 1 })
}
render() {
return (
<div>
<p>You clicked {this.state.count} times</p>
<button onClick={this.handleClick}>
Click me
</button>
</div>
);
}
}
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
}
handleClick = () => {
this.setState({ count: this.state.count + 1 })
}
render() {
return (
<div>
<p>You clicked {this.state.count} times</p>
<button onClick={this.handleClick}>
Click me
</button>
</div>
);
}
}
constructor(props) {
super(props);
this.state = {
count: 0
};
this.handleClick = this.handleClick.bind(this);
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleClick() {
// call setState
}
handleChange() {
// call setState
}
handleSubmit() {
// call setState
}
<button onClick={this.handleClick.bind(this)}>
We have a component that manage a state with a counter property, we have a handler that is attach to the onClick of a <button> which will invoke the React.Component’s setState method. We do use the extends React.Component which means we get access to all React.Component methods via this. So how come we can’t invoke this.setState. When using arrow functions, the engine will not “mutate” the this reference and will leave it as is, meaning whatever the this is pointing to at the wrapping execution context.
class App extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
countUp() {
this.setState(currentState => {
return { count: currentState.count + 1 };
});
}
render() {
const { count } = this.state;
return (
<div>
<button onClick={this.countUp}>{count}</button>
</div>
);
}
}
class App extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
countUp() {
this.setState(currentState => {
return { count: currentState.count + 1 };
});
}
render() {
const { count } = this.state;
return (
<div>
<button onClick={this.countUp.bind(this)}>{count}</button> </div>
);
}
}
class App extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
this.countUp = this.countUp.bind(this); }
countUp() {
this.setState(currentState => {
return { count: currentState.count + 1 };
});
}
render() {
const { count } = this.state;
return (
<div>
<button onClick={this.countUp}>{count}</button> </div>
);
}
}
class App extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
countUp = () => { this.setState(currentState => {
return { count: currentState.count + 1 };
});
}
render() {
const { count } = this.state;
return (
<div>
<button onClick={this.countUp}>{count}</button> </div>
);
}
}
class App extends React.Component {
state = { count: 0 };
countUp = () => {
this.setState(currentState => {
return { count: currentState.count + 1 };
});
};
render() {
const { count } = this.state;
return (
<div>
<button onClick={this.countUp}>{count}</button>
</div>
);
}
}
In this article we went over two ways to solve the React error message “this.setState is not a function”. If you have any questions or comments, feel free to leave them below! Where can we find this.setState then? The setState function is native to the React.Component class. Let’s look back at some code from Element.js: Notice the “extends Component” above. When we call the super() function in the constructor method, Element inherits all attributes of the React.Component class, including setState.
import { Element } from './Element'
import './index.css'
function App() {
return (
<div>
<Element/>
</div>
);
}
export default App;
import { Component, setState } from "react";
class Element extends Component {
constructor ( props ) {
super( props );
this.state = {
value: 1
};
}
handleClick() {
this.setState({
value: 2
});
}
render () {
return (
<div style={{
padding: '5px'
}}
onClick={this.handleClick}>
Value is: {this.state.value}
</div>
)
}
}
export { Element }
<div style={{
padding: '5px'
}}
onClick={this.handleClick}>
this.setState({
value: 2
});
class Element extends Component {
constructor(props) {
super(props);
this.state = {
value: 1
};
}
The reason why this error occurs is because of a concept called Closures in JavaScript. That means the scope/context of the function updateCounter and the class App are not the same. This means App and updateCounter have a different this. These kinds of issues will not occur while using functional components with hooks since it does not make use of this. In our case, we are trying to access this of the App class from within the function, which has its own this, which is currently undefined. Hence the error Cannot read properties of undefined.
1import React, { Component } from "react"2import "./App.css"3
4export default class App extends Component {5 constructor(props) {6 super(props)7
8 this.state = { counter: 0 }9 }10
11 updateCounter() {12 this.setState({ counter: this.state.counter + 1 })13 }14
15 render() {16 return (17 <div className="App">18 <button onClick={this.updateCounter}>19 Clicked {this.state.counter} Times20 </button>21 </div>22 )23 }24}
1import React, { Component } from "react"2import "./App.css"3
4export default class App extends Component {5 constructor(props) {6 super(props)7
8 this.state = { counter: 0 }9 }10
11 updateCounter = () => {12 this.setState({ counter: this.state.counter + 1 })13 }14
15 render() {16 return (17 <div className="App">18 <button onClick={this.updateCounter}>19 Clicked {this.state.counter} Times20 </button>21 </div>22 )23 }24}
1import React, { Component } from "react"2import "./App.css"3
4export default class App extends Component {5 constructor(props) {6 super(props)7
8 this.state = { counter: 0 }9
10 this.updateCounter = this.updateCounter.bind(this)11 }12
13 updateCounter() {14 this.setState({ counter: this.state.counter + 1 })15 }16
17 render() {18 return (19 <div className="App">20 <button onClick={this.updateCounter}>21 Clicked {this.state.counter} Times22 </button>23 </div>24 )25 }26}
Good day, folks. In this post, we'll examine how to find a solution to the programming challenge titled React Native Typeerror: This.setstate Is Not A Function.'this.setstate' Is Undefined) Solutions. React Native Typeerror: This.setstate Is Not A Function.'this.setstate' Is Undefined) Solutions We have shown how to address the React Native Typeerror: This.setstate Is Not A Function.'this.setstate' Is Undefined) Solutions problem by looking at a number of different cases.
componentDidMount() {
this.getZone()
}
setState(updater[, callback]) setState() enqueues changes to the component state and tells React that this component and its children need to be re-rendered with the updated state. This is the primary method you use to update the user interface in response to event handlers and server responses. setState , and React. useState create queues for React core to update the state object of a React component. So the process to update React state is asynchronous for performance reasons. That’s why changes don’t feel immediate. The setState() Method State can be updated in response to event handlers, server responses, or prop changes. This is done using the setState() method. The setState() method enqueues all of the updates made to the component state and instructs React to re-render the component and its children with the updated state.21-Jul-2022
Through the use of the programming language, we will work together to solve the _This2.Setstate Is Not A Function puzzle in this lesson. This is demonstrated in the code that follows.
constructor(props) {
super(props)
this.onClick = this.onClick.bind(this)
}
onClick() {
this.setState({
...
})
}
There are many ways to solve the same problem _This2.Setstate Is Not A Function. The other solutions are explored below.
bind the
function used in Class Component
The React.js "Uncaught TypeError: X is not a function" occurs when we try to call a value that is not a function as a function, e.g. calling the props object instead of a function. To solve the error, console.log the value you are calling and make sure it is a function. The pop() method should only be called on arrays, so trying to call it on any other type throws the "X is not a function" error because the pop function doesn't exist on the type. The best way to debug this is to console.log the value you are calling the function on and make sure it is of the correct type.
Copied!import {useState} from 'react';
// 👇️ should take props object and not setCount directly
// ⛔️ Uncaught TypeError: setCount is not a function
function Child(setCount) {
return (
<div>
<button onClick={() => setCount(current => current + 1)}>
Click
</button>
</div>
);
}
export default function App() {
const [count, setCount] = useState(0);
return (
<div>
<Child setCount={setCount} />
<h2>Count: {count}</h2>
</div>
);
}
Copied!import {useState} from 'react';
// 👇️ now component takes props object
// and calls function as props.setCount
function Child(props) {
console.log('props obj:', props);
return (
<div>
<button onClick={() => props.setCount(current => current + 1)}>
Click
</button>
</div>
);
}
export default function App() {
const [count, setCount] = useState(0);
return (
<div>
<Child setCount={setCount} />
<h2>Count: {count}</h2>
</div>
);
}
Copied!// 👇️ destructure the setCount prop
// and use it directly
function Child({setCount}) {
return (
<div>
<button onClick={() => setCount(current => current + 1)}>Click</button>
</div>
);
}
export default function App() {
const [count, setCount] = useState(0);
return (
<div>
<Child setCount={setCount} />
<h2>Count: {count}</h2>
</div>
);
}
Copied!
const obj = {};
console.log(typeof obj); // 👉️ "object"
console.log(Array.isArray(obj)); // 👉️ false
Copied!
const obj = {};
if (Array.isArray(obj)) {
console.log(obj.pop());
}
Pass a function instead of an object to setState to ensure the call always uses the most updated version of state (see below). Calls to setState are asynchronous - don’t rely on this.state to reflect the new value immediately after calling setState. Pass an updater function instead of an object if you need to compute values based on the current state (see below for details). Example of code that will not behave as expected:
incrementCount() {
// Note: this will *not* work as intended.
this.setState({
count: this.state.count + 1
});
}
handleSomething() {
// Let's say `this.state.count` starts at 0.
this.incrementCount();
this.incrementCount();
this.incrementCount();
// When React re-renders the component, `this.state.count` will be 1, but you expected 3.
// This is because `incrementCount()` function above reads from `this.state.count`,
// but React doesn't update `this.state.count` until the component is re-rendered.
// So `incrementCount()` ends up reading `this.state.count` as 0 every time, and sets it to 1.
// The fix is described below!
}
incrementCount() {
this.setState((state) => {
// Important: read `state` instead of `this.state` when updating.
return {
count: state.count + 1
}
});
}
handleSomething() {
// Let's say `this.state.count` starts at 0.
this.incrementCount();
this.incrementCount();
this.incrementCount();
// If you read `this.state.count` now, it would still be 0.
// But when React re-renders the component, it will be 3.
}