Reputation: 589
I am attempting to update state with information returned from an axios POST call. I am getting an error saying TypeError: Cannot read property 'setState' of undefined
. It sounds to me like this
is not usable from a API response.
submitData= () => {
axios.post("url", this.props.data)
.then(function (result) {
console.log(result,'success');
this.setState({
...this.state,
id: result.data.id
})
})
.catch(function (err) {
console.log(err, 'fail');
});
}
I can console log result.data.id
and it is the correct id. I am doing this all client side and I do not want to build out a server or use a reducer.
Upvotes: 0
Views: 378
Reputation: 1
Try making the .then
an anonymous function to bind this
.
submitData= () => {
axios.post("url", this.props.data)
.then((result) => {
console.log(result,'success');
this.setState({
...this.state,
id: result.data.id
})
})
.catch((err) => {
console.log(err, 'fail');
});
}
Upvotes: 0
Reputation: 11
You can also use async/await syntax and pass data as argument for greater flexibility/reusability. Try:
submitData = async (data) => {
try {
const result = await axios.post('url', data);
console.log('Success', result);
const { id } = result.data;
this.setState({
...this.state,
id,
});
} catch (err) {
console.log('Failure', err);
}
}
Upvotes: 1
Reputation: 365
In the callback function this
would be undefined (that's how this
in js works).
If you want an easy fix, just use arrow functions
submitData= () => {
axios.post("url", this.props.data)
.then(result => {
console.log(result,'success');
this.setState({
...this.state,
id: result.data.id
})
})
.catch(function (err) {
console.log(err, 'fail');
});
}
read more about this
https://hackernoon.com/javascript-es6-arrow-functions-and-lexical-this-f2a3e2a5e8c4
Upvotes: 0
Reputation: 1533
use arrow function in your callback like this :
submitData= () => {
axios.post("url", this.props.data)
.then((result) => {
console.log(result,'success');
this.setState({
...this.state,
id: result.data.id
})
})
.catch(function (err) {
console.log(err, 'fail');
});
}
Upvotes: 1