This is my composables/index.js file
export async function useData(endpoint, params, method = "POST") {
const authToken = useCookie("Authorization-Token");
try {
const response = await $fetch(
`${import.meta.env.VITE_API_BASE_URL}/v1/${endpoint}`,
{
method,
body: { ...params },
headers: {
"Client-Token": import.meta.env.VITE_API_CLIENT_TOKEN,
"Authorization-Token": authToken.value,
},
}
);
return response;
} catch (error) {
throw error;
}
}
I try to call it like this in my component
await useAsyncData(async () => {
try {
const workshopsFilters = [
{
column_name: "type",
operand: "IsEqualTo",
value: "workshop",
},
];
if (route.query.service) {
const servicesResponse = await useData("services/workshops/search", {
count: 0,
filters: [
{
column_name: "title",
operand: "IsEqualTo",
value: route.query.service,
},
],
});
and it will only fetch the data at the first render and if I refresh the page no requests will be sent anymore
but if I send the request like this everything will be fine:
await useAsyncData(async () => {
try {
const workshopsFilters = [
{
column_name: "type",
operand: "IsEqualTo",
value: "workshop",
},
];
if (route.query.service) {
const servicesResponse = await $fetch(
`${import.meta.env.VITE_API_BASE_URL}/v1/services/workshops/search`,
{
method: "POST",
body: {
count: 0,
filters: [
{
column_name: "title",
operand: "IsEqualTo",
value: route.query.service,
},
],
},
headers: {
"Client-Token": import.meta.env.VITE_API_CLIENT_TOKEN,
"Authorization-Token": authToken.value,
},
}
);
what is the problem
I’m quite new to nuxtjs and I don’t know how can I create a service-like function to handle my server side request so I can prevent from reading duplicated codes, I tried to write a custom composable for it and it went like this.