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