N
Nuxt4mo ago
bnason

Typing ref for $fetch

I need to create a ref that is typed for the return value of an api endpoint. I'll be updating it from a button $fetch request. I found this site Nuxt 3 server routes and Typescript that seems to give a good way to do it via an apiRef({ route: '/xx', method: 'get', defaultValue: null }) composable but it doesn't seem to be giving me the right typings. For instance, I have
const userInfo = apiRef({ route: '/api/userLookup`, method: 'post', defaultValue: null})

const doUserLookup = async () => {
const result = await $fetch(`/api/users/${userId}`, { method: 'post', body: '{"username":"foobar"}')
userInfo.value = result
}
const userInfo = apiRef({ route: '/api/userLookup`, method: 'post', defaultValue: null})

const doUserLookup = async () => {
const result = await $fetch(`/api/users/${userId}`, { method: 'post', body: '{"username":"foobar"}')
userInfo.value = result
}
Result is typed as such
const result: Simplify<SerializeObject<Response> | SerializeObject<UserLookupInfo> | undefined>
const result: Simplify<SerializeObject<Response> | SerializeObject<UserLookupInfo> | undefined>
but userInfo is typed this way
const userInfo: globalThis.Ref<{
readonly body: {
readonly locked: boolean;
} | null;
readonly headers: {};
readonly status: number;
readonly url: string;
readonly ok: boolean;
readonly redirected: boolean;
readonly statusText: string;
readonly type: ResponseType;
readonly bodyUsed: boolean;
} | {
...;
} | null | undefined>
const userInfo: globalThis.Ref<{
readonly body: {
readonly locked: boolean;
} | null;
readonly headers: {};
readonly status: number;
readonly url: string;
readonly ok: boolean;
readonly redirected: boolean;
readonly statusText: string;
readonly type: ResponseType;
readonly bodyUsed: boolean;
} | {
...;
} | null | undefined>
The weird thing is the userInfo.value = result does not give a typescript error. But trying to use {{ userInfo.username }} gives 'username' does not exist on ...
1 Reply
bnason
bnasonOP4mo ago
I figured this out.... turns out hopping between different frameworks comes with drawbacks lol I was accidentally returning a new Response instead of using setResponseStatus
Want results from more Discord servers?
Add your server