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

enable typescript strict mode #1010

Merged
merged 6 commits into from
Mar 9, 2021
Merged
Show file tree
Hide file tree
Changes from 3 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
56 changes: 28 additions & 28 deletions src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,11 @@ const cache = new Cache()

// error retry
function onErrorRetry(
_,
__,
config: ConfigInterface,
_: unknown,
__: string,
config: Readonly<Required<ConfigInterface>>,
revalidate: revalidateType,
opts: RevalidateOptionInterface
opts: Required<RevalidateOptionInterface>
): void {
if (!config.isDocumentVisible()) {
// if it's hidden, stop
Expand All @@ -32,7 +32,7 @@ function onErrorRetry(
}

// exponential backoff
const count = Math.min(opts.retryCount || 0, 8)
const count = Math.min(opts.retryCount, 8)
const timeout =
~~((Math.random() + 0.5) * (1 << count)) * config.errorRetryInterval
setTimeout(revalidate, timeout, opts)
Expand All @@ -43,36 +43,36 @@ function onErrorRetry(
// slow connection (<= 70Kbps)
const slowConnection =
typeof window !== 'undefined' &&
// @ts-ignore
navigator['connection'] &&
// @ts-ignore
['slow-2g', '2g'].indexOf(navigator['connection'].effectiveType) !== -1

// config
const defaultConfig: ConfigInterface = Object.assign(
{
// events
onLoadingSlow: () => {},
onSuccess: () => {},
onError: () => {},
onErrorRetry,
const defaultConfig = {
// events
onLoadingSlow: () => {},
onSuccess: () => {},
onError: () => {},
onErrorRetry,

errorRetryInterval: (slowConnection ? 10 : 5) * 1000,
focusThrottleInterval: 5 * 1000,
dedupingInterval: 2 * 1000,
loadingTimeout: (slowConnection ? 5 : 3) * 1000,
errorRetryInterval: (slowConnection ? 10 : 5) * 1000,
focusThrottleInterval: 5 * 1000,
dedupingInterval: 2 * 1000,
loadingTimeout: (slowConnection ? 5 : 3) * 1000,

refreshInterval: 0,
revalidateOnFocus: true,
revalidateOnReconnect: true,
refreshWhenHidden: false,
refreshWhenOffline: false,
shouldRetryOnError: true,
suspense: false,
compare: dequal,
refreshInterval: 0,
revalidateOnFocus: true,
revalidateOnReconnect: true,
refreshWhenHidden: false,
refreshWhenOffline: false,
shouldRetryOnError: true,
suspense: false,
compare: dequal,

isPaused: () => false
},
webPreset
)
isPaused: () => false,
...webPreset
} as const

export { cache }
export default defaultConfig
2 changes: 1 addition & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ export {
revalidateType,
RevalidateOptionInterface,
keyInterface,
responseInterface,
ResponseInterface as responseInterface,
shuding marked this conversation as resolved.
Show resolved Hide resolved
CacheInterface
} from './types'
export default useSWR
2 changes: 1 addition & 1 deletion src/libs/web-preset.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ const isDocumentVisible = () => {
return true
}

const fetcher = url => fetch(url).then(res => res.json())
const fetcher = (url: string) => fetch(url).then(res => res.json())

const registerOnFocus = (cb: () => void) => {
if (
Expand Down
17 changes: 10 additions & 7 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,23 +23,26 @@ export interface ConfigInterface<
isOnline: () => boolean
isDocumentVisible: () => boolean
isPaused: () => boolean
onLoadingSlow: (key: string, config: ConfigInterface<Data, Error>) => void
onLoadingSlow: (
key: string,
config: Readonly<Required<ConfigInterface<Data, Error>>>
) => void
onSuccess: (
data: Data,
key: string,
config: ConfigInterface<Data, Error>
config: Readonly<Required<ConfigInterface<Data, Error>>>
) => void
onError: (
err: Error,
key: string,
config: ConfigInterface<Data, Error>
config: Readonly<Required<ConfigInterface<Data, Error>>>
) => void
onErrorRetry: (
err: Error,
key: string,
config: ConfigInterface<Data, Error>,
config: Readonly<Required<ConfigInterface<Data, Error>>>,
revalidate: revalidateType,
revalidateOpts: RevalidateOptionInterface
revalidateOpts: Required<RevalidateOptionInterface>
) => void
registerOnFocus?: (cb: () => void) => void
registerOnReconnect?: (cb: () => void) => void
Expand Down Expand Up @@ -80,7 +83,7 @@ export type broadcastStateInterface<Data = any, Error = any> = (
error?: Error,
isValidating?: boolean
) => void
export type responseInterface<Data, Error> = {
export interface ResponseInterface<Data = any, Error = any> {
data?: Data
error?: Error
revalidate: () => Promise<boolean>
Expand All @@ -94,7 +97,7 @@ export type revalidateType = (
revalidateOpts: RevalidateOptionInterface
) => Promise<boolean>

export type actionType<Data, Error> = {
export type actionType<Data = any, Error = any> = {
data?: Data
error?: Error
isValidating?: boolean
Expand Down
88 changes: 44 additions & 44 deletions src/use-swr-infinite.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,77 +4,74 @@ import defaultConfig, { cache } from './config'
import SWRConfigContext from './swr-config-context'
import useSWR from './use-swr'

import { keyType, fetcherFn, ConfigInterface, responseInterface } from './types'
import {
keyType,
fetcherFn,
ConfigInterface,
ResponseInterface,
mutateCallback
} from './types'

type KeyLoader<Data = any> = (
index: number,
previousPageData: Data | null
) => keyType
type SWRInfiniteConfigInterface<Data = any, Error = any> = ConfigInterface<
Data[],
Error,
fetcherFn<Data[]>
> & {
interface SWRInfiniteConfigInterface<Data = any, Error = any>
extends ConfigInterface<Data[], Error, fetcherFn<Data[]>> {
initialSize?: number
revalidateAll?: boolean
persistSize?: boolean
}
type SWRInfiniteResponseInterface<Data = any, Error = any> = responseInterface<
Data[],
Error
> & {
interface SWRInfiniteResponseInterface<Data = any, Error = any>
extends ResponseInterface<Data[], Error> {
size: number
setSize: (
size: number | ((size: number) => number)
) => Promise<Data[] | undefined>
}

function useSWRInfinite<Data = any, Error = any>(
getKey: KeyLoader<Data>
): SWRInfiniteResponseInterface<Data, Error>
function useSWRInfinite<Data = any, Error = any>(
getKey: KeyLoader<Data>,
config?: Partial<SWRInfiniteConfigInterface<Data, Error>>
): SWRInfiniteResponseInterface<Data, Error>
function useSWRInfinite<Data = any, Error = any>(
getKey: KeyLoader<Data>,
fn?: fetcherFn<Data>,
config?: Partial<SWRInfiniteConfigInterface<Data, Error>>
): SWRInfiniteResponseInterface<Data, Error>
function useSWRInfinite<Data = any, Error = any>(
getKey: KeyLoader<Data>,
...options: any[]
...args:
| readonly [KeyLoader<Data>]
| readonly [KeyLoader<Data>, fetcherFn<Data>]
| readonly [
KeyLoader<Data>,
Partial<SWRInfiniteConfigInterface<Data, Error>>
]
| readonly [
KeyLoader<Data>,
fetcherFn<Data>,
Partial<SWRInfiniteConfigInterface<Data, Error>>
]
): SWRInfiniteResponseInterface<Data, Error> {
let _fn: fetcherFn<Data> | undefined,
_config: Partial<SWRInfiniteConfigInterface<Data, Error>> = {}

if (options.length > 1) {
_fn = options[0]
_config = options[1]
} else {
if (typeof options[0] === 'function') {
_fn = options[0]
} else if (typeof options[0] === 'object') {
_config = options[0]
}
}
const getKey = args[0]

const config: SWRInfiniteConfigInterface<Data, Error> = Object.assign(
const config = Object.assign(
{},
defaultConfig,
useContext(SWRConfigContext),
_config
args.length > 2
? args[2]
: args.length === 2 && typeof args[1] === 'object'
? args[1]
: {}
)
let {
// in typescript args.length > 2 is not same as args.lenth === 3
// we do a safe type assertion here
// args.length === 3
const fn = (args.length > 2
? args[1]
: args.length === 2 && typeof args[1] === 'function'
? args[1]
: config.fetcher) as fetcherFn<Data>

const {
initialSize = 1,
revalidateAll = false,
persistSize = false,
fetcher: defaultFetcher,
...extraConfig
} = config

const fn = typeof _fn !== 'undefined' ? _fn : defaultFetcher

// get the serialized key of the first page
let firstPageKey: string | null = null
try {
Expand Down Expand Up @@ -185,7 +182,10 @@ function useSWRInfinite<Data = any, Error = any>(
}, [swr.data])

const mutate = useCallback(
(data, shouldRevalidate = true) => {
(
data: Data[] | Promise<Data[]> | mutateCallback<Data[]> | undefined,
shouldRevalidate = true
) => {
if (shouldRevalidate && typeof data !== 'undefined') {
// we only revalidate the pages that are changed
const originalData = dataRef.current
Expand Down
Loading