swr icon indicating copy to clipboard operation
swr copied to clipboard

SWR should assert the data not be undefined if `isLoading` is false and `error` is null

Open cw1997 opened this issue 2 years ago • 1 comments

The sample code at here:

const {data, error, isLoading} = useSWR(['passport/session/get'], () => get_session())
if (!isLoading && error == null) {
  console.log(data.user_id)
}

image

In my opinion, I think if isLoading is false that means fetcher is executed finished, and if error is null, that means the executed result is successful, so data is must not undefined.

But I see the TypeScript report the data may be undefined in this case, is there any way to optimize the logic of typing narrow? Actually, I think in this condition, SWR should assert the data must not be undefined, is this an issue that can be improved?

Thank you very much!

Originally posted by @cw1997 in https://github.com/vercel/swr/discussions/2942

cw1997 avatar Apr 20 '24 11:04 cw1997

ref: https://github.com/vercel/swr/issues/2482

https://github.com/vercel/swr/pull/2175

cw1997 avatar Apr 24 '24 20:04 cw1997