Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nuxt3 using typescript with useFetch and transform option

I'm using useFetch to fetch an array of strings string[] with the transform option to transform it from array to object.

I tried the code below:

type ReceivedData = [string, string, string];

interface TransformedData {
    prop1: string,
    prop2: string,
    prop3: string
}

const { data, error } = await useFetch<ReceivedData>(
    `./jsonPath.json`,
    {
      transform: ([prop1, prop2, prop3]: ReceivedData): TransformedData  => ({
         prop1, prop2, prop3
      })
    }
);

I'm getting this error

Type '([prop1, prop2, prop3]: ReceivedData) => TransformedData' is not assignable to type '(res: ReceivedData) => ReceivedData'.

I pretty sure I'm messing something here, but Typescript is expecting the transform method to return the same data type it receives.

like image 518
Fennec Avatar asked Jun 28 '26 09:06

Fennec


2 Answers

I had the same issue. What worked for me was omitting the generic from the useFetch call and assigning the expected response type to the transform param

const { data, error } = await useFetch(
    `./jsonPath.json`,
    {
      transform: ([prop1, prop2, prop3]: ReceivedData): TransformedData  => ({
         prop1, prop2, prop3
      })
    }
);
like image 103
Tom T Avatar answered Jul 01 '26 03:07

Tom T


Currently, you could use it like this:

  type ReceivedData = [string, string, string]

  interface TransformedData {
    prop1: string
    prop2: string
    prop3: string
  }

  const transform = ([prop1, prop2, prop3]: ReceivedData): TransformedData => ({
    prop1,
    prop2,
    prop3,
  })

  const { data } = await useFetch<
    ReceivedData,
    Error,
    string,
    ReceivedData,
    typeof transform
  >(`./jsonPath.json`, {
    transform,
  })

Honestly speaking, I hope this will be improved in the future.

like image 36
some-user Avatar answered Jul 01 '26 03:07

some-user



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!