atinux / atinotes

An editable website with universal rendering on the edge.
https://notes.atinux.com
MIT License
154 stars 8 forks source link

custom useFetch has type bug #6

Closed kingyue737 closed 5 months ago

kingyue737 commented 5 months ago

Reproduction: https://stackblitz.com/edit/atinotes-1

Thanks for sharing the way to make a custom useFetch. But I found some type bugs with useAPI:

  1. When I set a default value in fetch options, it will raise error:
error TS2322: Type '() => never[]' is not assignable to type '() => Ref<null> | null'.
  Type 'never[]' is missing the following properties from type 'Ref<null>': value, [RefSymbol]
  1. With a non-null default value, useAPI still returns a nullable data:
error TS18047: 'data2.value' is possibly 'null'

Original useFetch has no such issue.

manniL commented 5 months ago

Seems reasonable to send a PR ;)

aaharu commented 5 months ago

Here is a workaround!

function useAPI<T>(
  url: string | (() => string),
  options: Omit<UseFetchOptions<T>, 'default'> & { default: () => T | Ref<T> },
) {
  return useFetch(url, {
    ...options,
  })
}
const { data: data2 } = useAPI<{ bug: string }[]>('/', {
  default: () => [],
})
data2.value.push({ bug: 'bug' })

The useFetch returns data null if the default option is undefined, so the error can be resolved by making default required in the options of the useAPI.

atinux commented 5 months ago

Updated in the article thank you!