I am trying to use useFetch() once on the server and a second time in the client, in one composable.
So far I have not been able to get this to work.
A reproduction of my attempt can be found here: https://stackblitz.com/edit/github-o9ivmk?file=composables%2FuseTwoStepFetch.ts
It is the second useFetch() with server:false that I cannot get to return something -- it always returns null.
Is there a way to get this working? An example somewhere?
The composable looks like this:
// Simplified example.
// Fetch data in two steps:
// 1. Quickly get a small number of records (3)
// 2. Get all the rest of the data
export async function useTwoStepFetch() {
const nuxtApp = useNuxtApp();
const result = ref([] as any[]);
// get the first 3 records
// use useFetch() so this call can be done on the server
const body1 = { take: 3 };
await nuxtApp.runWithContext(async () => {
const { data }: any = await useFetch('/api/hello', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: body1,
watch: false,
server: true,
lazy: false,
});
// Put data in the result
console.log('data.value (1)', data.value);
result.value = data.value;
});
// get the rest of the data
// ** HERE I WANT TO BE SURE THAT IT RUNS ONLY ON CLIENT **
const body2 = { skip: 3 };
// ** NO AWAIT BECAUSE WE WANT TO RETURN THE RESULT BEFORE THE CALL FINISHED **
nuxtApp.runWithContext(async () => {
const { data }: any = await useFetch('/api/hello', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: body2,
watch: false,
/* server:true, lazy:false works, but that is not what I want */
server: false,
lazy: true,
});
console.log('data.value (2)', data.value);
result.value.splice(result.value.length, 0, ...(data.value || []));
});
return result;
}