0👍
✅
Typically you just need to move the Axios parts into a module and leave the consumption of the data to your components.
// services/rest.js
import axios from "axios";
const rest = axios.create({
// better still, use env vars to define your URLs
baseURL: "http://localhost:8080/rest/tctresidents/v1",
});
// This is a function
export const getResidents = async () => {
try {
// the request path will be appended to the baseURL
return (await rest.get("/Residents")).data;
} catch (err) {
// see https://axios-http.com/docs/handling_errors
console.error(err.toJSON());
throw new Error(err.message);
}
};
Then in your components / store / literally anywhere…
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);
}
},
};
Source:stackexchange.com