Reputation: 125
The following code is for a single post, axios fetches the current post ID and stores the result in post array. Keep in mind, only ONE post is stored since this is fetching a single post. The ID and date display properly but if I try to display nested items like rendered content it doesn't work.
Here is what the API json result looks like:
constructor(props) {
super(props);
this.state = {
post: []
};
}
getPost() {
axios
.get('single_post_api')
.then(response => {
this.setState({
post: response.data
});
});
}
componentDidMount() {
this.getPost();
}
render() {
const data = this.state.post;
return (
<View>
<Text>{data.date}</Text>
<Text>{data.slug}</Text>
///Neither of these work///
<Text>{data.content.rendered}</Text>
<Text>{data.content[0]}</Text>
////////////////////////////
</View>
);
}
Upvotes: 0
Views: 190
Reputation: 906
Try this.
render() {
// If we run into a null, just render it as if we had an empty array.
const posts = (this.state ?? this.state.posts) ? this.state.posts : [];
return (
<View>
(posts.map((post, index) => (
<View key={index}>
<Text>{post.date}</Text>
<Text>{post.slug}</Text>
<Text>{post.content ? post.content.rendered : ""}</Text>
</View>
));
</View>
);
}
Upvotes: 2