Re:SWR 2.0 – React Hooks for Data Fetching
by azangru on Friday December 09, 2022 @06:23PM
(#33927849)
> I think the big difference between react-query and its competitors like SWR is typescript support.
Redux-toolkit-query has a fantastic typescript support.
Re:SWR 2.0 – React Hooks for Data Fetching
by teaearlgraycold on Friday December 09, 2022 @06:07PM
(#33927669)
I just rig up a wrapper around swr to make it have the types I want. Only takes a few lines of code.
Re:SWR 2.0 – React Hooks for Data Fetching
by v0idzer0 on Friday December 09, 2022 @07:33PM
(#33928409)
How is it different than…?
const { data } = useSWR<MyDataType>(“/my/data”)
Re:SWR 2.0 – React Hooks for Data Fetching
by emptysea on Friday December 09, 2022 @10:23PM
(#33929553)
With `useSWR` the return type is
export interface SWRResponse<Data = any, Error = any> {
/**
* The returned data of the fetcher function.
*/
data: Data | undefined
/**
* The error object thrown by the fetcher function.
*/
error: Error | undefined
mutate: KeyedMutator<Data>
isValidating: boolean
isLoading: boolean
}
https://github.com/vercel/swr/blob/14956a840ac9b75fe321bf846...so if I check `isLoading` in my component then typescript isn't able to narrow/refine the type to something more specific since it isn't a sum type.
While with react-query, it's a proper sum type that can be differentiated by checking `isLoading`.
The type is actually quite long so here's just a bit
export type QueryObserverResult<TData = unknown, TError = unknown> =
| QueryObserverIdleResult<TData, TError>
| QueryObserverLoadingErrorResult<TData, TError>
| QueryObserverLoadingResult<TData, TError>
| QueryObserverRefetchErrorResult<TData, TError>
| QueryObserverSuccessResult<TData, TError>
export interface QueryObserverLoadingResult<TData = unknown, TError = unknown>
extends QueryObserverBaseResult<TData, TError> {
data: undefined
error: null
isError: false
isIdle: false
isLoading: true
isLoadingError: false
isRefetchError: false
isSuccess: false
status: 'loading'
}
https://github.com/TanStack/query/blob/9b21609350d9ad41faf5c...The key point in the type above is `isLoading: true` and `data: undefined`, which means if I check `isLoading === true`, then typescript knows the data is not available.
SWR doesn't provide these guarantees.
React-query has proper sum types for its hook’s return value