I am trying to access variables from json in react component.
This is JSON I am getting:
{
"id": 5,
"title": "Hello",
"text": "Hello, this is my first article...",
"picture": "pic",
"comments": [],
"user": {
"id": 3,
"name": "Anonim",
"password": "123456"
}
}
The attached user is person who created the post. The attached comments is list of comments related to this post. In routing I am doing the following:
<Switch>
<Route path='/' exact component={PostsPage} />
<Route path='/:id' exact component={PostProfilePage} />
</Switch>
In react class component
class PostProfile extends Component {
constructor(props){
// Pass props to the parent component
super(props);
// Set initial state
this.state = {
// State needed
post: []
};
}
componentDidMount() {
this.fetchPost();
}
fetchPost() {
const {match} = this.props
const id = match.params.id
console.log(id)
fetch('/'+id)
.then(res => {
return res.json();
})
.then(data => {
this.setState({
post: data
});
})
.catch(err => {
console.log(err);
});
}
render() {
return (
<div>
<li> {this.state.post.title} </li>
<li> {this.state.post.text} </li>
</div>
)
}
}
export default withRouter(PostProfile)
does not work
<li> {this.state.post.user.name} </li>
<li> {this.state.post.comments...} </li>
Why I cannot access user and comments? And is it possible to get user and comments in different components? (not calling the fetch method again and again)?
Thank you in advance!
this.state.postyield anything?console.log(this.state.post.user.name)andconsole.log(this.state.post.user)in render. it showsthis.state.post.userbut not the first one.