I am a newbie to ReactJS and was trying to fetch the data from JSON file. I have created 2 files one is products.json and app.jsx. I can get the result in console.log()
[{…}]
0
:
{title: "Product Title", img: "./p-1.jpg", des: "DES1", rs: 599}
length
:
1
__proto__
:
Array(0)
but it's rendering in view. I sometimes get undefined, or the data itself is not populating.
here's my react code.
import React from 'react';
import Request from 'superagent';
import ReactDOM from 'react-dom';
import {
Container,
Col,
Row,
Card
} from 'react-bootstrap';
class App extends React.Component {
render() {
return (
<div className="container">
<Header />
<Content />
<Footer />
</div>
);
}
}
// Header starts
class Header extends React.Component {
componentDidMount() {
//alert('Header');
}
render() {
return (
<header>
<h1>Header !! </h1>
</header>
);
}
}
// Header ends
// Content starts
class Content extends React.Component {
constructor() {
super();
this.state = {
data: []
}
}
componentDidMount() {
var url = "./products.json";
Request.get(url)
.then((res) => {
console.log(res.body.data);
console.log(res.body.data.title);
//this.setState({data: data.conversations});
this.setState({
PTitle: res.body.title,
PImg: res.body.img,
PDesc: res.body.des,
PRs: res.body.rs
});
})
.catch(function (err) {
alert(err);
// err.message, err.response
});
}
render() {
return (
<ul>
{
this.state.data.map((key, i) =>
<ProductList key={i} products={key} />)
}
</ul>
)
}
}
// Content ends
// Footer starts
class Footer extends React.Component {
render() {
return (
<div>
Footer !!
</div>
)
}
}
// Footer ends
// Products Starts
class ProductList extends React.Component {
render() {
return (
2. - <li>{PTitle}</li>
)
}
}
// Products Ends
export default App;
this.state.dataanywhere? Am I missing it?this.setState({data: data.conversations});. Is that intentional?res.body.data.conversations.