Data fetching and Mock Server
REST API
For data fetching in the Uno template follow this documentation Axios Mock Adapter
axios is used for calling the api, you can use any library you want.
This is the API Function Hook You can use this hook from any where in the page.
import axios, { AxiosRequestConfig } from "axios";
import { onMounted, ref } from "vue";
export function useFetch(url: string, config?: AxiosRequestConfig) {
const error = ref("");
const data = ref(null);
const isLoading = ref(false);
const getFetchData = async () => {
try {
isLoading.value = true;
const response = await axios.get(url, config);
data.value = response.data;
} catch (err) {
console.error(err);
error.value = "Something went wrong";
} finally {
isLoading.value = false;
}
};
onMounted(getFetchData);
return { error, isLoading, data };
}
API Call using useFetch.ts hook
import { useFetch } from "@/hooks/useFetch";
const { isLoading, data: user } = useFetch("/api/users", {
params: { id: +route.params.id }
});
Mock server
Fake API example
- We used a mock server for handling management data like users, orders, products and invoices. If you would like to use your own API then you have to remove this from the project.
- Now I showing you one fake API Example based on users data. __mock__/users
import Mock from "../mock";
import { users, statues } from "./users";
// GET ALL USERS & GET SINGLE USER BY ID
Mock.onGet("/api/users").reply(({ params }) => {
if (params && params.id) {
return [200, users.find((user) => user.id === +params.id)];
}
return [200, users];
});