Reputation: 467
You can find my JSON data on this link. What I am having trouble doing is acquiring article
data from React.
My code is below. I did not include the JSON get request code in my question as it's not entirely consequential. I used the jQuery $.getJSON method to replace the state of fulldata
with the array. So assume that the data is fully there under fulldata
.
getInitialState:function(){
return { fulldata: {forthem:[ {articles: [] } ]} }
},
viewer:function(){
return (<ul>
{this.state.fulldata.forthem[0].articles.map(function(makeit, o){
return <li key={o}>{makeit.article}</li>})}
</ul>)
},
What this existing code allows me to do is acquire the first set of articles under emjayweb
. However, if I modify the code to this.state.fulldata.forthem[1]
I cannot get the second set of articles
under cnn
. I get a Cannot read property map of undefined
error.
Upvotes: 1
Views: 97
Reputation: 3593
Try this one... so instead of using an external loop for getting the data, we use array's map
and reduce
function.
const articles = data.forthem.map(item =>
item.articles.map(article => article)
).reduce((list, current) =>
list.concat(current)
);
Working example below...
const data = {
"forthem": [
{
"therefore": "emjayweb",
"theresym": "emj",
"articles": [
{
"number": "1",
"article": "How to Strengthen Your Password",
"url": "",
"pubdate": ""
}, {
"number": "2",
"article": "Second Article",
"url": "",
"pubdate": ""
}
]
}, {
"therefore": "CNN",
"theresym": "cnn",
"articles": [
{
"number": "3",
"article": "Work It",
"url": "",
"pubdate": ""
}
]
}
]
};
class MyComponent extends React.Component {
render() {
return <div>
<h2>Articles</h2>
<ul>
{this.props.articles.map(item => <li key={item.number}>{item.article}</li>)}
</ul>
</div>
}
}
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
articles: []
}
}
componentWillMount() {
const articles = data.forthem.map(item =>
item.articles.map(article => article)
).reduce((list, current) =>
list.concat(current)
);
this.setState({ articles });
}
render() {
return <div>
<h1>React Demo</h1>
<MyComponent articles={this.state.articles}/>
</div>
}
}
ReactDOM.render(<App/>, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
Upvotes: 1