Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to specify useFetch data return type in Nuxt

I am fetching data from an API in Nuxt3. I am using typescript and I wish to define the type of data that I will get. How do I specify this?

<script lang="ts" setup>
  interface APIBody {
    /* properties defined here */
  }

  const {data} = await useFetch("api_url here")
</script>

<template>
 {{ data.name.officialName }}
<template>

I get an error in the template where I am displaying data.name.officialName

Property 'name' does not exist on type 'never'

However, while running the code in the browser, the website works fine.

Edit I tried the following code but I am receiving a different error now.

<script lang="ts" setup>
  interface APIBody {
    /* properties defined here */
  }

  const typedData = ref<APIBody[]>()
  const {data} = await useFetch("api_url here")
  typedData.value = data as APIBody[] // -> error here
</script>

<template>
 {{ data.name.officialName }}
<template>

The error in this case is:

Conversion of type 'Ref<Pick<unknown, never>>' to type 'APIBody[]' may be a mistake because neither type sufficiently overlaps with the other.

like image 678
Nishant Jalan Avatar asked Dec 01 '25 23:12

Nishant Jalan


2 Answers

You can give a type to useFetch to define the return type

Like:

  interface APIBody {
    /* properties defined here */
  }

  const {data} = await useFetch<APIBody>("api_url here")
like image 82
Under_Koen Avatar answered Dec 04 '25 11:12

Under_Koen


It's my working example in Nuxt 3.9.0:

// /api/test.post.ts
export default defineEventHandler(async (event) => {
    const body = await readBody(event);
    return { body };
});

In any component or page:

<script lang="ts" setup>
import type { AsyncData } from 'nuxt/app';
import type { FetchError } from 'ofetch';
    
interface Body { key: string };
    
const { data: { value: { body } }, error } = await useFetch('/api/test', {
  method: 'post',
    body: {
      key: 'value',
    }
  }) as AsyncData<{ body: Body }, FetchError>;
    
// now you're getting body's properties without ts-errors
console.log(body.key); // value
</script>
like image 44
genter_morgan Avatar answered Dec 04 '25 11:12

genter_morgan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!