I'm trying to create a composable function in my nuxt 3 project to fetch some date from my strapi cms. I want to simplify the fetch function in all components and pages i have to a simple method with 2 or 3 parameters, like path or an optional pick argument. the composable function should then execute the useFetch with the baseURL and the strapi apiToken from the runtimeConfig and also a transform function after getting back the response.
This is a working code snipped from a vue page to test:
<template>
<div id="dev">
<h1>Dev</h1>
<h3>Test Fetches</h3>
<p v-if="pending">Pending</p>
<p v-else-if="data">Data: {{ data }}</p>
<p v-else-if="error">Error: {{ error }}</p>
</div>
</template>
<script setup>
const headers = new Headers();
const runtimeConfig = useRuntimeConfig()
if (process.server) console.log(runtimeConfig);
headers.append('Authorization', `Bearer: ${runtimeConfig.apiToken}`)
const { data: data, pending, error, refresh } = await useFetch('/api/[content-type]?populate=deep', {
baseURL: runtimeConfig.public.apiBaseUrl,
headers,
transform: (response) => {
return response.data;
},
// pick: ['id']
})
if (process.server) console.log(data);
</script>
I tried to move this to a composable fetchStrapi.js:
export const fetchStrapi = async (path, pick = []) => {
const headers = new Headers();
const runtimeConfig = useRuntimeConfig()
if (process.server) console.log(runtimeConfig);
headers.append('Authorization', `Bearer: ${runtimeConfig.apiToken}`)
const { data: data, pending, error, refresh } = await useFetch(path, {
baseURL: runtimeConfig.public.apiBaseUrl,
headers,
transform: (response) => {
return response.data;
},
pick
})
if (process.server) console.log(data);
return { data: data, pending, error, refresh }
}
and run it from the dev page:
<template>
<div id="dev">
<h1>Dev</h1>
<h3>Test Fetches</h3>
<p v-if="pending">Pending</p>
<p v-else-if="data">Data: {{ data }}</p>
<p v-else-if="error">Error: {{ error }}</p>
</div>
</template>
<script setup>
const { data: data, pending, error, refresh } = fetchStrapi('/api/[content-type]?populate=deep');
if (process.server) console.log(data);
</script>
but the content in data is not displayed and the console of the server tells:
undefined
RefImpl {
__v_isShallow: false,
dep: undefined,
__v_isRef: true,
_rawValue: {},
_value: {}
}
I already added a await before the fetchStrapi function which results in Data: being displayed in the browser, but still not the answer i am expecting
My nuxt.config.ts looks like this:
// https://nuxt.com/docs/api/configuration/nuxt-config
export default defineNuxtConfig({
devtools: { enabled: true },
runtimeConfig: {
apiToken: '',
public: {
apiBaseUrl: 'https://[urlToStrapi]',
}
}
})
API Token comes from a .env file.
What's wrong?
Thank you for any help!