Search code examples
arraysjsonvue.jsaxiosconcatenation

Multiple Axios Requests Into Vue


I have two different json endpoints I'm using in a Vue JS app. Currently I'm display's posts in a home view. Then using Vue router I'm creating a details view with more specific post info. I would like to for comments to show up from endpoint /comments to appear in the details view if the comment id matches the post id.

posts /posts

comments /comments

import axios from 'axios'

const instance = axios.create({
  baseURL: 'https://jsonplaceholder.typicode.com/'
})
const basePost = '/posts'
const baseComments = '/comments'

export default {
  fetchPosts () {
    return instance
      .get(basePost)
      .then(response => response.data)
  }
}

How would I concatenate both arrays into one and then set that to retrieve posts and comments in a view?


Solution

  • Since axios get returns promise, so u can call both parallel and get the promises to resolve using Promise.all.

    Example 1: Using Promise.all

    //const axios = require("axios");
    const instance = axios.create({
      baseURL: "https://jsonplaceholder.typicode.com/",
    });
    const basePost = "/posts";
    const baseComments = "/comments";
    const service = {
      fetchPosts() {
        const promises = [instance.get(basePost), instance.get(baseComments)];
        return Promise.all(promises).then(([posts, comments]) => [
          posts.data,
          comments.data,
        ]);
      },
    };
    service.fetchPosts().then(console.log);
    // export default service;
    .as-console-row {
      color: blue !important;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.2/axios.js"></script>

    Note: If you want in series way meaning post first then comment u can use async-await.

    Example 2: Using async-await

    //const axios = require("axios");
    const instance = axios.create({
      baseURL: "https://jsonplaceholder.typicode.com/",
    });
    const basePost = "/posts";
    const baseComments = "/comments";
    const service = {
      async fetchPosts() {
        const posts = await instance.get(basePost).then((x) => x.data);
        const comments = await instance.get(baseComments).then((x) => x.data);
        //console.log(posts, comments);
        return [posts, comments];
      },
    };
    // export default service;
    
    service.fetchPosts().then(console.log);
    .as-console-row {
      color: blue !important;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.2/axios.js"></script>