Do you want to request a feature or report a bug?
Bug report
What is the current behavior?
TypeError: Cannot read property 'updater' of undefined
To reproduce
import React, {Component} from 'react';
import logo from './logo.svg';
import './App.css';
import axios from 'axios';
class App extends Component {
constructor() {
super();
this.state = {
colors: []
};
this.onFileChange = this.onFileChange.bind(this);
}
onFileChange(e) {
const { setState } = this;
if (this.refs.fileInput.files && this.refs.fileInput.files[0]) {
var FR = new FileReader();
FR.onload = (e) => {
axios.post('example.com', {
image: e.target.result
})
.then(function (response) {
setState(() => ({
colors: []
}))
})
.catch(function (error) {
console.log(error);
});
};
FR.readAsDataURL(this.refs.fileInput.files[0]);
}
}
render() {
return (
<div className="App">
<div className="App-header">
<img src={logo} className="App-logo" alt="logo"/>
<h2>Welcome to React</h2>
</div>
<input type='file' ref="fileInput" onChange={e => this.onFileChange(e)}/>
<img id="img" src=""/>
<div id="base"></div>
{
this.state.colors.map(function(c){
const styles = { height: 200, width: 200, backgroundColor: c.hex };
return (<div styles={styles}></div>);
})
}
</div>
);
}
}
export default App;
I cant provide the url of the post but I guess it doesnt matter.
Which versions of React, and which browser / OS are affected by this issue? Did this work in previous versions of React?
Chrome Version 58.0.3029.96 (64-bit)
"react": "^15.5.4",
"react-dom": "^15.5.4"
It's not a bug.
You need to bind this
to setState
or use arrow function as a callback.
const setState = this.setState.bind(this)
or
axios.post('example.com', {
image: e.target.result
})
.then((response) => {
this.setState(() => ({
colors: []
}))
})
.catch(function (error) {
console.log(error);
});
It doesn't make sense to re-use setState in a different context, not sure why it's a static method.
Most helpful comment
It's not a bug.
You need to bind
this
tosetState
or use arrow function as a callback.or