D
D
dmitriu2562021-08-03 18:26:21
React
dmitriu256, 2021-08-03 18:26:21

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);
            })
    }


How to implement this task using NextJs
In the getInitialProps method, it was possible to execute only one request to receive a post.
Code snippet on NextJs
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});
}

I will be grateful for your help!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
dmitriu256, 2021-08-03
@dmitriu256

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 question

Ask a Question

731 491 924 answers to any question