In my React app I'm using axios to return data from an API.
api-helper.js
export const getData = async () => {
axios
.get(API_DOMAIN)
.then(response => {
const resp = response.data;
console.log(resp);
})
.catch(error => console.log('get error', error));
};
In the console log, the JSON data is returned correctly:
{
"content": {
"code": "CAT33",
"name": "Death Star ",
"slug": "death-start-",
"trustFriendlySlug": false,
"description": "",
"facetFilters": [
...// additional data
However, in my parent component when I try to use this data in ComponentDidMount
, It is returning an HTML string instead of the JSON data:
data: "<!DOCTYPE html>↵<html lang="en">↵ <head>↵
headers: {accept-ranges: "bytes", connection: "keep-alive", content-encoding: "gzip", content-type: "text/html; charset=UTF-8", date: "Fri, 08 Jan 2021 15:49:27 GMT", …}
request: XMLHttpRequest {readyState: 4, timeout: 0, withCreden
parentComponent.js
import { getData } from '../../utils/api-helper';
class parentComponent extends Component {
constructor(props) {
super(props);
this.state = {
content: {
code: '',
name: '',
facetFilters: [],
},
};
componentDidMount() {
axios.get(getData()).then(result => {
console.log('result', result);
this.setState({ result });
});
}
}
I thought using axios.get
in componentDidMount
along with the request from my api-helper would display the same result. What is the correct way to import data. I've looked at examples such as How to get valid JSON response from axios library using nodeJS & Can't set state in react
However, unlike those answers, I am trying to pass the data down from my parent component into other components. What is the correct way to handle this data?