I'm trying to pass data from my JSON file to my ReactJS app, but receiving the following error:
TypeError: Cannot read property
'mainPage'of undefined
If I try to console.log siteData only, it will work well. I am guessing the problem is probably to do with accessing the object parameters
Can you tell me what I'm doing wrong?
Here is my JSON object:
{
"data": {
"mainPage": {
"navBar": ["HR", "HR1", "HR2"],
"name": "Name one",
"agency": "agency one"
},
"secondPage": {
"rank": 2,
"name": "Name Two",
"agency": "agency two"
},
"thirdPage": {
"rank": 3,
"name": "Name Three",
"agency": "agency three"
}
}
}
My .jsx file:
import React from 'react';
import axios from 'axios';
import logo from '../img/company_logo.png';
import '../css/header.scss';
export default class Header extends React.Component {
constructor() {
super();
this.state = {
siteData: {},
};
}
componentDidMount() {
axios.get('./data.json')
.then((res) => {
this.setState({
siteData: res.data,
});
})
.catch((err) => {
console.log(err);
});
}
render() {
// console.log(this.state);
const { siteData } = this.state;
console.log(siteData.data.mainPage);
return (
<div className="headerWrapper">
<a href=".../public/index.html">
<img src={logo} alt="company_logo" id="companyLogo" />
</a>
<ul>
<li>Navbar_1</li>
<li>Navbar_2</li>
<li>Navbar_3</li>
</ul>
</div>
);
}
}
siteData.datais undefined. You are probably missing a level of nesting. Try withsiteData.mainPage?siteData.datait will show me objectsiteData.mainPage