Had the data in JSON in a previous build of my app but (with the help of StackOverflow community) redesigned how I call my API to fix various other breaking errors.
This is what I just tried. I log both the "regular" output and the attempt at converting it to JSON. The non-json output comes up as "{data: Array}" in my console while the JSON is undefined.
componentDidMount() {
axios
.get(
"API_KEY"
)
.then((res) => {
const data = res.data
const json = data.json
this.setState({ data, loading: false });
console.log(json);
console.log(data)
});
}
And here is my other attempt:
componentDidMount() {
axios.get("API_KEY").then((res) => {
const data = res.data;
this.setState({ data, loading: false });
console.log(data);
console.log(JSON.parse(JSON.stringify(data)));
});
}
All your help and advice is greatly appreciated! :)
I would suggest a better syntax using ES6.
const componentDidMount = async () => {
let { data } = await axios.get("API_KEY")
// Your data by default should be object or array.
// Regardless, both should worked fine.
console.log(data)
// In case it is just string and not undefined
if (data && typeof data !== 'object') {
data = JSON.parse(data)
}
this.setState({ data, loading: false })
}
Otherwise, try using breakpoint or console.log in the first place after getting the result. If the result is undefined, perhaps the promise is yet to resolve.