Answer the question
In order to leave comments, you need to log in
How to combine two ajax requests in getInititalProps in NextJs?
I am mastering the NextJs library and faced the problem of how to combine two ajax requests?
Testing was carried out using JsonFakeApi
Need to get a post by id, as well as the author of the post (username)
Post
User
Previously implemented this task using React
Code snippet
constructor(props) {
super(props);
this.state = {
post: {},
author: '',
comments: []
};
}
componentDidMount() {
let id = this.props.match.params.id;
axios(`https://jsonplaceholder.typicode.com/posts/${id}`)
.then(data => {
const authorId = data.data.userId;
const postId = data.data.id;
this.setState({post: data.data});
//Логин пользователя
this.getUserName(authorId);
//Получение списка комментариев к посту
this.getPostComments(postId);
})
.catch(error => {
console.log(error);
})
}
//получение логина пользователя
getUserName = id => {
axios(`https://jsonplaceholder.typicode.com/users/${id}`)
.then(data => {
this.setState({author: data.data.username});
})
.catch(error => {
console.log(error);
})
}
Post.getInitialProps = async ({query, req}) => {
//console.log(query);
if(!req){
return ({post: null})
}
const response = await fetch(`https://jsonplaceholder.typicode.com/posts/${query.id}`);
const data = await response.json();
return ({post: data});
}
Answer the question
In order to leave comments, you need to log in
My solution
Post.getInitialProps = async ({query, req}) => {
//console.log(query);
if(!req){
return ({post: null})
}
const postApi = await fetch(`https://jsonplaceholder.typicode.com/posts/${query.id}`);
const post = await postApi.json();
//Получаем id пользователя
const userId = post.userId;
const userApi = await fetch(`https://jsonplaceholder.typicode.com/users/${userId}`);
const user = await userApi.json();
return ({post: post, name: user.username});
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question