Answer the question
In order to leave comments, you need to log in
Is the request asynchronous correctly?
Is the asynchronous request correctly framed in this component? Or compnentDidMount should be issued as a synchronous request, and the getUserName function should be left asynchronous?
1) The request in componentDidMount gets the post description from the server. We write the result in state
2) Request to get the user's login by its userId from the previous request. - method getUserName Post
request data looks like
{
"userId": 1,
"id": 2,
"title": "qui est esse",
"body": "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla"
}
{
"id": 1,
"name": "Leanne Graham",
"username": "Bret",
"email": "[email protected]",...
constructor(props) {
super(props);
this.state = {
post: {},
author: ''
};
}
async componentDidMount() {
let id = this.props.match.params.id;
try{
const response = await axios(`https://jsonplaceholder.typicode.com/posts/${id}`);
const data = await response.data;
const authorId = data.userId;
this.setState({post: data});
//Логин пользователя
this.getUserName(authorId);
} catch (e) {
console.log(e);
}
}
//получение логина пользователя
getUserName = async (id) => {
const response = await fetch(`https://jsonplaceholder.typicode.com/users/${id}`);
if (!response.ok) {
console.log(response.status);
}
const data = await response.json();
const result = await data.username;
this.setState({author: result});
}
render() {
return (
<div style={postStyle}>
<h1>Post Details {this.props.match.params.id}</h1>
<h2>{this.state.post.title}</h2>
<p>{this.state.post.body}</p>
<div>
<span>User:
<Link to={'/users/' + this.state.post.userId}>{this.state.author}</Link>
</span>
</div>
</div>
);
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question