How can we use vuex and vuejs to fetch data from an external '.js' file in Vuejs?

I am currently facing an issue when trying to call the API from my external.js file in Vuejs. I am using axios to make the API call and then displaying the data using v-for inside my component. However, I keep getting an error stating that axios is defined but never used.

The endpoint URL that I want to call inside my data.js file is:

If you want to see the code that is working, you can check it out at this link: https://codesandbox.io/s/blissful-northcutt-wze8i?file=/src/components/data.js

data.js

export default {
  methods: {
    mydata() {
      axios.get("https://randomuser.me/api/").then((response) => this.response);
    }
  }
};

HelloWorld.vue

<template>
  <div>
    <div v-for="list in lists" :key="list.id">
      {{ list.name }}<br />{{ list.location }}
    </div>
  </div>
</template>

<script>
import axios from "axios";
import { mydata } from "./data";
export default {
  name: "HelloWorld",
  data() {
    return {
      lists: mydata,
    };
  },
};
</script>

Answer №1

To begin, start by exporting a function in the simplest way possible:

import axios from "axios";

export const mydata = () => {
  return axios.get("https://randomuser.me/api/").then((response) => response);
}

Don't forget to import axios in your external JavaScript file as it is being used there and not in the component file.

Next, since your API will return a Promise, you need to wait for the result - this can be achieved by calling the API in the mounted method and populating the list property once it's ready.

<template>
  <div>
    <div v-for="list in lists" :key="list.id.value">
      {{ list.name.title }} {{ list.name.first }}
      <br />{{ list.location.country }}
    </div>
  </div>
</template>

<script>
import { mydata } from "./data";

export default {
  name: "HelloWorld",
  data() {
    return {
      lists: [],
    };
  },
  mounted() {
    mydata().then(r => { this.lists = r.data.results });
  }
};
</script>

Finally, keep in mind that the object returned from the API may differ slightly from your expectations, so make sure to adjust the HTML code accordingly for real-world scenarios.

Answer №2

To make a call to the endpoint API, Axios can be utilized as shown below:

<template>
  <div>
    <div v-for="user in users" :key="user .id">
      {{ user.name }}<br />{{ user.username}}
    </div>
  </div>
</template>


<script>
import axios from "axios";
// import { mydata } from "./data";
export default {
  name: "HelloWorld",
  data() {
    return {
      // lists: mydata,
      users: []
    };
  },
  mounted () {
   axios
  .get('https://jsonplaceholder.typicode.com/users/2')
  .then(response => (this.users = response))
  .catch(error => console.log(error))
  }
};
</script>

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

Issue encountered with react-toolbox 2.0-beta.6's ThemeProvider not functioning as expected

I have been attempting to modify the color-primary and color-accent variables in react-toolbox using react-toolbox-themr, but without success. I have created a simple git repository to showcase this issue. Below is my react-toolbox-themr.config.json: { ...

The code isn't able to make use of the MongoDB FIND method

When I attempt to search for items in a collection using the console with db.DB_NAME.find({ x: y }, it works perfectly. However, when trying to do the same in the code, it doesn't seem to work. It's worth mentioning that the findOne method works ...

Offspring maintain a certain position within the larger framework of their parent on a

When resizing the parent wrap container, how can I ensure that the pin (red dot) on the image maintains its relative position? To see the issue, resize the wrap container. #wrap{ position: absolute; width: 100%; height: 100%; top: 0; l ...

Creating a dynamic multidimensional array or object in AngularJS: tips and tricks

Below is the code snippet where I am attempting to dynamically construct an associative array in angularJs: $scope.details = {"profilesFound": [ "https: //twitter.com/alexandreagular", "https: //twitter.com/?profile_id=46130006", "https: //f ...

Guide on waiting for promise from UI Router Resolve within an Angular 1.5 Component

Help needed with Angular 1.5 Component and Resolve for data retrieval Seeking guidance on utilizing Resolve to fetch data. Plunker: https://plnkr.co/edit/2wv4YWn8YQvow6FDcGV0 <!DOCTYPE html> <html ng-app="app"> <head> <meta c ...

The navigation bar's HTML hue

Currently working on a website design and looking to replicate the unique color gradient effect seen in the top navigation bar of Virgin America airlines' website (refer to the image linked below). Interested in any CSS/HTML techniques that could help ...

What is the best way to retrieve route data based on route name in VueJs?

When working with VueJs, I have found that I can easily access the data of the current route. However, I have encountered a situation where I need to access the data of a different route by its name. Let's say I have defined the following routes: [ ...

What is the best way to execute multiple functions in sequence and halt the process if any of them encounter an error?

I am working with multiple Javascript functions that manipulate the DOM and run ajax requests. My goal is to execute these functions sequentially, one after the other, and only proceed if none of them return false from their ajax request. If any function r ...

Creating a TypeScript rule/config to trigger an error when a React Functional Component does not return JSX

I've encountered a recurring issue where I forget to include a return statement when rendering JSX in a functional component. Here's an example of the mistake: const Greetings = function Greetings({name}) { <div>Greetings {name}</div& ...

Effortlessly showcase JSON data in an HTML owl carousel

Is there a way to display JSON data in HTML format? I have a JSON file containing reviews from Facebook, and I would like to showcase them on my website. Each review should be placed in its own div element. The JSON data below is extracted from the Faceboo ...

What are some effective methods for incorporating a bootstrap theme into a VueJS project?

Are there alternative methods for integrating a bootstrap theme into VueJs without utilizing bootstrap-vue and having to modify the entire template? What is the ideal approach for including the bootstrap.min.css file, along with any related font files? I ...

JavaScript capable of storing vast quantities of data

Currently, I am receiving file chunks in byte format from my server and combining them into one variable on my frontend for downloading later. Unfortunately, I am unable to modify the server setup which sends files sliced into chunks. The issue arises whe ...

How to switch the code from using $.ajax() to employing $.getJSON in your script

How can I convert this code from using AJAX to JSON for better efficiency? AJAX $('#movie-list').on('click', '.see-detail', function() { $.ajax({ url: 'http://omdbapi.com', dataType: 'json', d ...

Having trouble transforming an HTTP response into JSON format?

Utilizing my own API, I am fetching data using the following code: fetch('/guidebook/api/peak-data/') .then(response => response.json()) .then(response => JSON.stringify((response))) .then(data => { ...

Exploring Angular JS: Understanding the Framework's Structure and FAQs

After diving into the world of AngularJS and familiarizing myself with its tutorial and documentation, I find myself in need of guidance on organizing the structure of my project. My goal is to create a single page app with different main sections such as ...

Breaking down an array into alphabetical sections using React and Typescript

I have a large array of strings containing over 100 words. I have already sorted the array in alphabetical order, but now I need to group or split the array into a hash array called hashMap<String(Alphabet), List<String>>. This will allow me to ...

Creating a custom request for the Upload component in Ant Design Vue requires a specific set of steps and

I attempted to implement the solution provided in How should customRequest be set in the Ant Design Upload component to work with an XMLHttpRequest? but it doesn't seem to be working for me in Ant Design Vue. Could someone provide an example, please? ...

Ways to remove any messages containing URLs that are not www.youtube.com or www.twitter.com

Recently, I have encountered a significant issue with Discord Scam Links in my server. I attempted the following approach: if(message.content.includes("discordscam.com")) { message.delete() } However, this method is not effective as it onl ...

Utilizing jQuery to target elements that are dynamically generated upon successful AJAX response

When handling dynamically created elements on ajax success, I encountered an issue. I have multiple checkboxes within a table and when the table content is replaced on ajax success, I am unable to select any new checkbox. While it is possible to trigger cl ...

Obtain information using AJAX calls with jQuery Flot

Having an issue with jQuery Flot that I need help resolving. PHP output (not in JSON format): [[1, 153], [2, 513], [3, 644]] ~~ [[1, 1553], [2, 1903], [3, 2680]] Here is the jQuery call: $.ajax({ url: 'xxx.php', success: function (dat ...