swr icon indicating copy to clipboard operation
swr copied to clipboard

typeof 'data' is always optional even with 'fallbackData' provided.

Open kjsik11 opened this issue 2 years ago • 2 comments

Bug report

Description / Observed Behavior

type of data

Expected Behavior

type of data should be Data(not Data | undefined) if fallbackData has provided in type Data.

Repro Steps / Code Example

const { data } = useSWR<string>('my-key', {
  fallbackData: 'hello world',
});

image

SWR version. 1.0.0

kjsik11 avatar Aug 30 '21 09:08 kjsik11

Any plans to resolve this issue?

It's so confusing especially while I am using Shared Hook State with SWR which is updated feature at [email protected] (using undefined for fetcher)

for example use case,

export function useEmail() {
  const { data: email, mutate: setEmail } = useSWR('@email-key', {
    fallbackData: '',
    fetcher: undefined,
  });

  return [email!, setEmail] as const;
}

kayk1m avatar Sep 22 '21 07:09 kayk1m

Is there any update on this issue?

tachibanayu24 avatar Mar 28 '22 01:03 tachibanayu24

It is weird that data can still be undefined even though fallbackData is set. Because of this issue, it is quite inconvenient to use useSWR and typeScript together.

dnjsgur0629 avatar Nov 14 '22 07:11 dnjsgur0629

Still an issue in v2.1.5.

image

Anyway coercion is always a workaround, but it is still strange because #2301 seems to have fixed this with BlockingData, and my config parameter does extend { fallbackData: Data }.

mrcaidev avatar Apr 27 '23 10:04 mrcaidev

Still an issue in v2.1.5.

image

Anyway coercion is always a workaround, but it is still strange because #2301 seems to have fixed this with BlockingData, and my config parameter does extend { fallbackData: Data }.

dont specify generic, it need fetcher and fallbackData to infer the type

BoneTM avatar Jun 13 '23 07:06 BoneTM

dont specify generic, it need fetcher and fallbackData to infer the type

Thanks for the info! It works:

  // string | undefined
  const { data } = useSWR<string>("/api", { suspense: true })

  // string
  const { data } = useSWR("/api", fetcher<string>, { suspense: true })

peterhirn avatar Jul 24 '23 13:07 peterhirn