itemprop="text">
I am calling service that is using
XML, so i want to parse XML to JSON and the JSON data set as my react state but i am
getting.
TypeError: Cannot read
property 'setState' of
undefined
axios
.get(session_url)
.then(function(response) {
parseString(response.data, (err, result) => {
if (err) {
throw
err;
} else {
this.setState({
odm:
result.data,
loading: false,
});
}
});
})
.catch(function(error) {
console.log(error);
});
class="post-text" itemprop="text">
class="normal">Answer
You're
mixing and matching function()
s that don't capture
this
and arrow (=>
) functions which
do.
Simply use arrow functions everywhere and
the this
(that's your React component) will be properly
captured:
axios
.get(session_url)
.then(response => {
parseString(response.data, (err, result) => {
if (err)
{
throw err;
} else {
this.setState({
odm: result.data,
loading: false,
});
}
});
})
.catch(error =>
{
console.log(error);
});
Better yet, if you
can, use an async
function:
// promisified version
of `parseString`:
const parseStringP = data =>
new
Promise((resolve, reject) =>
parseString(response.data, (err, result)
=> {
if (err) return reject(err);
resolve(result);
}),
);
//
...
try {
const response = await
axios.get(session_url);
const result = await
parseStringP(response.data);
this.setState({
odm: result.data,
loading: false,
});
} catch (error)
{
console.log(error);
}
No comments:
Post a Comment