Skip to content

feat: add isSuccess field into SWRResponse #4074

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

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 18 additions & 1 deletion src/_internal/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -466,7 +466,7 @@ type SWRConfigurationWithOptionalFallback<Options> =
? Omit<Options, 'fallbackData'> & Pick<Partial<Options>, 'fallbackData'>
: Options

export interface SWRResponse<Data = any, Error = any, Config = any> {
export interface SWRBaseResponse<Data = any, Error = any, Config = any> {
/**
* The returned data of the fetcher function.
*/
Expand All @@ -478,8 +478,25 @@ export interface SWRResponse<Data = any, Error = any, Config = any> {
mutate: KeyedMutator<Data>
isValidating: boolean
isLoading: IsLoadingResponse<Data, Config>
/**
* A derived boolean from {@link isLoading} and {@link error} which indicates if the request has completed successfully.
*/
isSuccess: boolean
}
export interface SWRSuccessResponse<Data = any, Error = any, Config = any>
extends SWRBaseResponse<Data, Error, Config> {
data: Data
isSuccess: true
}
export interface SWRErrorResponse<Data = any, Error = any, Config = any>
extends SWRBaseResponse<Data, Error, Config> {
error: Error
isSuccess: false
}

export type SWRResponse<Data = any, Error = any, Config = any> =
| SWRSuccessResponse<Data, Error, Config>
| SWRErrorResponse<Data, Error, Config>
export type KeyLoader<Args extends Arguments = Arguments> =
| ((index: number, previousPageData: any | null) => Args)
| null
Expand Down
5 changes: 5 additions & 0 deletions src/index/use-swr.ts
Original file line number Diff line number Diff line change
Expand Up @@ -746,6 +746,11 @@ export const useSWRHandler = <Data = any, Error = any>(
get isLoading() {
stateDependencies.isLoading = true
return isLoading
},
get isSuccess() {
stateDependencies.isLoading = true
stateDependencies.error = true
return !isLoading && isUndefined(error)
}
} as SWRResponse<Data, Error>
}
Expand Down
12 changes: 12 additions & 0 deletions test/type/isSuccess.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import useSWR from 'swr'
import { expectType } from './utils'

export function useIsSuccess() {
const fetcherResult = 'helloWorld'
const { data, isSuccess } = useSWR('key', () => fetcherResult)
expectType<typeof data>(fetcherResult)
expectType<typeof data>(undefined)
if (isSuccess) {
expectType<typeof data>(fetcherResult)
}
}