score:406
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');
score:1
Use from arrow function to handle action.
score:1
This is mainly incompatibility problem between react, react-dom, and enzyme.
Try install the following as I did to solve the problem:
[...]
"react": "^18.0.0-beta-f320ef88f-20211116",
"react-dom": "16.14.0",
"enzyme": "^3.11.0",
"enzyme-adapter-react-16": "^1.15.6"
[...]
score:1
In my case, the problem was that I was sending the state and setstate as props to a child component but there was a typo in setstate
score:2
If you're doing this and still having an issue, my problem is I was calling two variables the same name.
I had companies
as an object brought in from Firebase, and then was trying to call this.setState({companies: companies})
- it wasn't working for obvious reasons.
score:3
I have the same error of
TypeError: setState is not a function
but the cause is silly. Posting it as a response here to hopefully save people who might be making the same mistake.
Instead of
const { state, setState } = React.useState(false);
Use
const [ state, setState ] = React.useState(false);
Square brackets and not curly brackets!
score:6
Here THIS context is getting changed. Use arrow function to keep context of React class.
VK.init(() => {
console.info("API initialisation successful");
VK.api('users.get',{fields: 'photo_50'},(data) => {
if(data.response){
this.setState({ //the error happens here
FirstName: data.response[0].first_name
});
console.info(this.state.FirstName);
}
});
}, function(){
console.info("API initialisation failed");
}, '5.34');
score:7
Now in react with es6/7 you can bind function to current context with arrow function like this, make request and resolve promises like this :
listMovies = async () => {
const request = await VK.api('users.get',{fields: 'photo_50'});
const data = await request.json()
if (data) {
this.setState({movies: data})
}
}
With this method you can easily call this function in the componentDidMount and wait the data before render your html in your render 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.
score:9
You no need to assign this to a local variable if you use arrow function. Arrow functions takes binding automatically and you can stay away with scope related issues.
Below code explains how to use arrow function in different scenarios
componentDidMount = () => {
VK.init(() => {
console.info("API initialisation successful");
VK.api('users.get',{fields: 'photo_50'},(data) => {
if(data.response){
that.setState({ //this available here and you can do setState
FirstName: data.response[0].first_name
});
console.info(that.state.FirstName);
}
});
}, () => {
console.info("API initialisation failed");
}, '5.34');
},
score:10
Now ES6 have arrow function it really helpful if you really confuse with bind(this) expression you can try arrow function
This is how I do.
componentWillMount() {
ListApi.getList()
.then(JsonList => this.setState({ List: JsonList }));
}
//Above method equalent to this...
componentWillMount() {
ListApi.getList()
.then(function (JsonList) {
this.setState({ List: JsonList });
}.bind(this));
}
score:14
use arrow functions, as arrow functions point to parent scope and this will be available. (substitute of bind technique)
score:16
You just need to bind your event
for ex-
// place this code to your constructor
this._handleDelete = this._handleDelete.bind(this);
// and your setState function will work perfectly
_handleDelete(id){
this.state.list.splice(id, 1);
this.setState({ list: this.state.list });
// this.setState({list: list});
}
score:40
you could also save a reference to this
before you invoke the api
method:
componentDidMount:function(){
var that = this;
VK.init(function(){
console.info("API initialisation successful");
VK.api('users.get',{fields: 'photo_50'},function(data){
if(data.response){
that.setState({ //the error happens here
FirstName: data.response[0].first_name
});
console.info(that.state.FirstName);
}
});
}, function(){
console.info("API initialisation failed");
}, '5.34');
},
score:53
React recommends bind this in all methods that needs to use this of class
instead this of self function
.
constructor(props) {
super(props)
this.onClick = this.onClick.bind(this)
}
onClick () {
this.setState({...})
}
Or you may to use arrow function
instead.
score:153
You can avoid the need for .bind(this) with an ES6 arrow function.
VK.api('users.get',{fields: 'photo_50'},(data) => {
if(data.response){
this.setState({ //the error happens here
FirstName: data.response[0].first_name
});
console.info(this.state.FirstName);
}
});
Source: stackoverflow.com
Related Query
- React setState inside of a function this is undefined
- React Arrow Function Component - setState is not defined
- How to not use setState inside render function in React
- Why react calls function in subcomponents event when this subsomponents not rendered?
- React useState() & useContext() - TypeError: setState is not a function - What am I doing wrong?
- React - Calling setState in a function that's called from another class throws not a function exception
- When Using Redux Saga with React Get This Error .. Uncaught TypeError: getPosts is not a function
- Component not mounted when setState called in arrow function in React with ES2016
- setState in react function not updating in promise method
- react useState and setState claims calendarList.push is not a function
- React Hooks setState function not setting state
- React why is this simple array map function not returning anything?
- Getting this error while using React router TypeError: type.toUpperCase is not a function
- React setState is not a function
- React setState function not reached thus not working
- setState not a function after binding this
- React setState is not a function upon adding JSON?
- React useEffect: setState in return function does not update state in time
- TypeError: records.map is not a function - First React project, stuck on this error with API
- TypeError: setState is not a function in React
- React SetState not working till second render if HTML element updated inside a function
- React Hooks setState function is not a function error
- React onclick setState not working with arrow function
- setState for react function component not updated my state
- setState function in reactjs is not setting state. How to overcome this problem?
- Parameters of my function in React child component are not being passed to the parent component's function. Why is this happening?
- React JS TypeError - this is not a function
- React Hook setState function not updating value
- react setState function is not workin
- React setState opposite boolean in map function not changing state
More Query from same tag
- How to pass props to a styled component in emotion? Using TypeScript
- how to export the return table data to a csv file using react js
- How to overwrite fetch using Javascript?
- How to save data as int using mongodb compass and koa js. Value automatically convert into String
- How to edit the icons and properties of the edit and remove buttons on the editable Material-table?
- React Suspense not working as expected when fetching data
- Show A Div Section From A Selected Option - Stateless Components
- React state hook with an object
- Typescript React event handler types
- How can I create a count down number for setTimeout in react
- How to pass props to {this.props.children}
- Adding a keyboard arrow navigation to Carousel Reactjs
- Objects are not valid as a React child use an array instead
- How to User Login With Wordpress using React Native
- React - carousel
- Updating state as a nested object
- Defining schema for dynamic rendering of dependent dropdowns/input fields
- How Should I Dispatch Actions When Using React Hooks?
- Unable to run React Native Project on simulator after updating to Xcode 12
- How can i render an image came from MongoDB in binary data on React.js?
- Material-ui Typography with router link always underlined
- How do I display base64 inside map loop(assumption) in ReactJS
- Jsx build a table and limiting items
- React-router - Link firing too soon
- Async Actions Reducer Typings using typesafe-actions
- Bug: React does not recognize the allowTransparency prop on a DOM element
- Webpack doesn't process CSS background image
- React ES6 component modal API
- LocalStorage not working properly ReactJS
- Can you pass different Material-ui icons as props?