Using Vue to make a REST API call in a JavaScript file

I have been trying to convert an Axios API call from a Vue page into a standalone module that can be reused multiple times in my app. Unfortunately, all my attempts so far have failed and I'm not sure if it's because I lack experience working with standalone JavaScript modules or if there's another issue at play.

Below is the working Vue code:

<template>
  <div>
    <ul v-if="posts && posts.length">
      <li v-for="post of posts">
        <p><strong>{{post.resID}}</strong></p>
        <p>{{post.Name}}</p>
      </li>
    </ul>

    <ul v-if="errors && errors.length">
      <li v-for="error of errors">
        {{error.message}}
      </li>
    </ul>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  name: "GetMxList",
  data() {
    return {
      posts: [],
      errors: []
    }
  },

  // Fetches posts when the component is created.
  created() {
    axios.get("http://localhost:8080/rest/...")
    .then(response => {
      // JSON responses are automatically parsed.
      this.posts = response.data
    })
    .catch(e => {
      this.errors.push(e)
    })
  }
}
</script>

My aim is to create a reusable module similar to rest.js and then consume it in Pinia. The idea is to load the data once and use it multiple times throughout the app. Currently, I have managed to make it work with a static load as shown in the following code snippet. The getJSONList function calls a JS module that returns a JSON formatted response which is then stored in MyList for use across the application using Pinia mapping.

actions: {

    async fetchList() {
      
      const data = await getJSONList();
      this.Mylist = data;
    },

After many iterations, I have come up with a solution that does not throw any errors, even though it doesn't return anything:

import axios from 'axios';

export function getJSONList() {
    
    const rest = axios.create({
        baseURL: "http://localhost:8080/rest/", // alternatively, use environmental variables
      });

    const getPosts = async () => {
    try {
      return (await rest.get("http://localhost:8080/rest/")).data;
    } catch (err) {
      console.error(err.toJSON());  
      throw new Error(err.message);
    }
  };
    return (getPosts);
}

Answer №1

To simplify your code, consider moving the Axios functionality into a separate module and letting your components handle the data consumption.

// services/rest.js
import axios from "axios";

const rest = axios.create({
  // For better organization, consider using environment variables for URLs
  baseURL: "http://localhost:8080/rest/tctresidents/v1",
});

// This function retrieves residents' data
export const getResidents = async () => {
  try {
    return (await rest.get("/Residents")).data;
  } catch (err) {
    console.error(err.toJSON());
    throw new Error(err.message);
  }
};

You can then use this module in your components, store, or anywhere else:

import { getResidents } from "./path/to/services/rest";

export default {
  data: () => ({ residents: [], errors: [] }),
  async created() {
    try {
      this.residents = await getResidents();
    } catch (err) {
      this.errors.push(err);
    }
  },
};

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

My ReactNative Android application is experiencing significant lag, is there anyone who can assist me in resolving this issue?

Currently, I'm tackling a reactnative android app project and have noticed a significant drop in performance. Unfortunately, I am clueless about the root cause of this issue. Could it be related to the navigator or are there other underlying factors a ...

chart.js version 3 does not display the correct date data on the time axis

Struggling to make chart.js work with a time axis is proving to be quite challenging for me. The code I have is as follows: <html> <head> <script src="https://cdn.jsdelivr.net/npm/moment"></script> <script src="https://cdnjs.clo ...

How to verify that the user is using the most up-to-date version of the application in React Native

Currently, I am focused on the application and have implemented API endpoints that return the latest version along with information on whether the update is mandatory. Within the application flow, a GET request is sent to these API endpoints to check the ...

Error: Vue Prop is undefined and cannot be utilized within a v-for loop when using TypeScript and decorators

Hey there, I'm currently utilizing Vue along with typescript and facing an issue with props in v-for where it's not rendering anything. Check out the code snippet below for reference I've experimented with computed props, setting default va ...

Tips for sending data from a JSP to a Servlet with Javascript

My code creates an array of circular buttons with dynamic values. When clicked, these buttons get deleted and their values are stored in a JavaScript object array. I need to send these deleted button values to a servlet once my task is complete. To do this ...

The issue of Angular UI Bootstrap buttons not updating persists even after the removal of an

My Radio-bottoms are powered by an Array for a Multi-Choice answer setup. <div ng-repeat="option in options"> <div> <button type="button" style="min-width: 100px" class="btn btn-default" ng-model="question.answer" btn-radio="' ...

Implementation of multiple angular guards causing a crash on the page

I have been attempting to implement separate guards for distinct pages. Essentially, I am checking a boolean parameter to determine if a user is logged in or not. Below are the two guard.ts codes that I am using: export class IsAuthenticatedGuard implemen ...

Failure to display React component on screen

I have developed a React microfrontend application consisting of two sub-apps rendered through the container/ project. Both sub-apps render perfectly in isolation on localhost:8083. However, when attempting to view them via localhost:8080/dashboard, I am p ...

Assigning a one-of-a-kind identifier to a cell within a table that was dynamically created using JavaScript and

When using JavaScript to create table cells and rows and populate them with information from a JSON file, I encounter an issue where the unique ids assigned to the table cells in my code are undefined. This causes problems when trying to reference these id ...

Creating image filters using an object in jQuery

I am faced with a challenge where I have multiple image tags nested within a div that has the class google-image-layout. Each image is equipped with various data attributes, including: data-anger="0" data-disgust="0" data-facedetected="0" data-fear="0" da ...

Conceal descendant of list item and reveal upon clicking

In my responsive side menu, there is a submenu structured like this: .navbar ul li ul I would like the child menus to be hidden and only shown when the parent menu is clicked. Although I attempted to achieve this with the following code, it was unsucces ...

Display a dropdown menu when clicking on a close button in a single element using Vanilla JavaScript

I'm currently in the process of learning Javascript and trying to grasp the concept of events and selectors. My aim is to have a close button that, when clicked, triggers a specific dropdown related to the card it's attached to. I plan to achie ...

Building a like/dislike feature in Angular

Here is a snippet of code I have that includes like and dislike buttons with font-awesome icons: <ng-container *ngFor="let answer of question.answers"> <p class="answers">{{answer.text}} <i class="fa fa-hand-o-le ...

exciting command: templateUrl

I am in need of assistance with a particular issue: I am trying to configure settings for an application and would like to utilize the UI-Bootstrap accordion. This is the HTML code I have so far: <accordion close-others="oneAtATime"> <accor ...

Using the useRef hook to target a particular input element for focus among a group of multiple inputs

I'm currently working with React and facing an issue where the child components lose focus on input fields every time they are re-rendered within the parent component. I update some state when the input is changed, but the focus is lost in the process ...

The IDE is showing an error, but Jest is able to run it flawlessly

I recently created a Jest unit test for a TypeScript function called checkEmail, which internally uses showAlert. The showAlert function in the utils.ts file looks like this: export const showAlert = (message: string) => { toast(message); }; In my ...

Can you explain the significance of this code snippet 'true <=> false'?

Today I came across this piece of code: true <=> false. I'm a bit confused by it and don't really understand how it works. If anyone could shed some light on this expression for me, I would greatly appreciate it. For reference, this code ...

How to initialize data in Vue.js components

I'm working on a Map.vue component and I need to update its data in Vue.js. However, I'm struggling to figure out how to do this: <template> <div> <div class="google-map" :id="mapName"> </div> </div> < ...

What is the best way to create an event listener that can identify when a boolean variable switches to true?

Let's say we have a variable var menu_ready = false;. We also have an ajax function that will change menu_ready to true once the ajax operations are completed: // code snippet to set up event listener $(...).load(..., function() { ... menu_r ...

The margin-top property in CSS is not functioning as intended for a specific pixel value when applied to

I'm having trouble with positioning an icon using margin-top: -35px; under #menu. When I click on the icon, the side navigation bar doesn't work properly. However, if I adjust it to -15px, the side navigation bar displays correctly. Can someone h ...