Markeem
Markeem
NNuxt
Created by Markeem on 6/14/2023 in #❓・help
Wrapping $fetch in composable with default options while retaining type safety
I found this somewhere in the nitro sourcecode:
import { $fetch } from "ofetch";
import { $Fetch, NitroFetchRequest } from "../types";
if (!globalThis.$fetch) {
globalThis.$fetch = $fetch as $Fetch<unknown, NitroFetchRequest>;
}
import { $fetch } from "ofetch";
import { $Fetch, NitroFetchRequest } from "../types";
if (!globalThis.$fetch) {
globalThis.$fetch = $fetch as $Fetch<unknown, NitroFetchRequest>;
}
So I changed my composable to:
import type { NitroFetchRequest } from 'nitropack'

export function useFetchWithDefaultOptions<T extends NitroFetchRequest>(url: T) {
return $fetch<unknown, T>(url, {
headers: {
defaultHeader: 'value',
},
})
}
import type { NitroFetchRequest } from 'nitropack'

export function useFetchWithDefaultOptions<T extends NitroFetchRequest>(url: T) {
return $fetch<unknown, T>(url, {
headers: {
defaultHeader: 'value',
},
})
}
And it seems to work on first look. Maybe someone from the team can confirm if this is valid ?
2 replies