T dhanunjay
T dhanunjay

Reputation: 820

Using vuex/vuejs, How to call api from external '.js' file in Vuejs?

I am calling the api from my external.js file and then i am calling it inside of my component using the v-for to display the required data. During this process, I am unable to call the api. Everytime i am getting error as axios defined but never used.

This is my endpoint url, Which i want to call inside of data.js file:- https://randomuser.me/api/

Issue when trying to call the api from external.js file in Vuejs

Code working:- 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>

Upvotes: 1

Views: 1409

Answers (2)

1_bug
1_bug

Reputation: 5717

First, you should export function in simpliest way:

import axios from "axios";

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

Remember to import axios in your external js file because you use it there, not in component file.

Second, your API will return Promise, so you have to wait for result - you can do it by calling API in mounted method and filling property list when it will be 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>

Last but not least, an object returned from api is little different than you expect, so I have adjusted html code for real case.

Upvotes: 2

Husnul Jahneer
Husnul Jahneer

Reputation: 282

You can call the endpoint API using Axios like this.

<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>

Upvotes: 0

Related Questions