Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

data and error cannot be undefined by themselves #113

Closed
0x009922 opened this issue Nov 25, 2020 · 1 comment
Closed

data and error cannot be undefined by themselves #113

0x009922 opened this issue Nov 25, 2020 · 1 comment

Comments

@0x009922
Copy link

Problem

interface SomeDataType {
  foo: string;
}

async function fetcher(): Promise<SomeDataType> {
  return { foo: 'test' }
}

const { data, error } = useSWRV('some-key', fetcher);

// const data: Ref<SomeDataType | undefined> | undefined
// const error: Ref<any> | undefined

Why can the values data and error themselves be undefined? This is not really what is happening. They are always some kind of Ref with values, they cannot be undefined by themselves. The code snippets below confirm this.

// https://github.com/Kong/swrv/blob/03b853191cb00d48f51f8edbdbbe3216e8847bf5/src/use-swrv.ts#L203

stateRef = reactive({
  data: undefined,
  error: undefined,
  isValidating: true,
  key: null
}) as StateRef<Data, Error>

// -- snip --

// https://github.com/Kong/swrv/blob/03b853191cb00d48f51f8edbdbbe3216e8847bf5/src/use-swrv.ts#L389

const res: IResponse = {
  ...toRefs(stateRef),
  mutate: (data, opts: revalidateOptions) => revalidate(data, {
    ...opts,
    forceRevalidate: true
  })
}

return res

This code shows that data and error will always be Ref<Data> and Ref<Error>, not Ref<Data> | undefined and Ref<Error> | undefined.

I think the IResponse interface should be fixed:

// now
export interface IResponse<Data = any, Error = any> {
  data?: Ref<Data | undefined>;
  error?: Ref<Error | undefined>;
  isValidating: Ref<boolean>;
  mutate: () => Promise<void>;
}

// should be
export interface IResponse<Data = any, Error = any> {
  data: Ref<Data | undefined>;
  // ^ remove '?'
  error: Ref<Error | undefined>;
  // ^ remove '?'
  isValidating: Ref<boolean>;
  mutate: () => Promise<void>;
}

Anyway, thanks for the swrv, it's great!

@darrenjennings
Copy link
Contributor

This is a duplicate of #74. @lqdsld can you provide a reproduction repo that shows the type error?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants