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

types: infer provider type as cache type #1506

Closed
wants to merge 5 commits into from
Closed
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
3 changes: 2 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,5 +21,6 @@ export {
Fetcher,
MutatorCallback,
Middleware,
Arguments
Arguments,
DefaultProvider
} from './types'
22 changes: 16 additions & 6 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,11 +31,10 @@ export type Fetcher<Data = unknown, SWRKey extends Key = Key> =
: never

// Configuration types that are only used internally, not exposed to the user.
export interface InternalConfiguration {
cache: Cache
export interface InternalConfiguration<P> {
cache: P
mutate: ScopedMutator
}

export interface PublicConfiguration<
Data = any,
Error = any,
Expand Down Expand Up @@ -89,7 +88,10 @@ export interface PublicConfiguration<
isVisible: () => boolean
}

export type FullConfiguration = InternalConfiguration & PublicConfiguration
export type FullConfiguration<Provider = Cache> = InternalConfiguration<
Provider
> &
PublicConfiguration

export type ProviderConfiguration = {
initFocus: (callback: () => void) => (() => void) | void
Expand Down Expand Up @@ -160,7 +162,7 @@ export type State<Data, Error> = {
}

export type Mutator<Data = any> = (
cache: Cache,
cache: Cache<Data>,
key: Key,
data?: Data | Promise<Data> | MutatorCallback<Data>,
shouldRevalidate?: boolean
Expand Down Expand Up @@ -234,8 +236,16 @@ export type StateUpdateCallback<Data = any, Error = any> = (
isValidating?: boolean
) => void

export interface Cache<Data = any> {
export interface ICache<Data = any> {
get(key: Key): Data | null | undefined
set(key: Key, value: Data): void
delete(key: Key): void
}

export type DefaultProvider = Map<string | null, any>
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why string | null instead of just string?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

because swr/infinite has some case that cache key is string | null

like

  const resolvePageSize = useCallback((): number => {
    const cachedPageSize = cache.get(pageSizeCacheKey)
    return isUndefined(cachedPageSize) ? initialSize : cachedPageSize

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That feels like a bug (facepalm)


export type Cache<T = DefaultProvider, Data = any> = T extends ICache<Data>
? T
: never

export type CacheProvider<Data = any> = (cache: Cache<Data>) => Cache<Data>
4 changes: 2 additions & 2 deletions src/utils/cache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,9 @@ const revalidateAllKeys = (
}

export const initCache = <Data = any>(
provider: Cache<Data>,
provider: Cache,
options?: Partial<ProviderConfiguration>
): [Cache<Data>, ScopedMutator<Data>, () => void] | undefined => {
): [Cache, ScopedMutator<Data>, () => void] | undefined => {
// The global state for a specific provider will be used to deduplicate
// requests and store listeners. As well as a mutate function that bound to
// the cache.
Expand Down
37 changes: 24 additions & 13 deletions src/utils/config-context.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,10 @@
import { createContext, createElement, useContext, useState, FC } from 'react'
import {
createContext,
createElement,
useContext,
useState,
ReactElement
} from 'react'
import { cache as defaultCache } from './config'
import { initCache } from './cache'
import { mergeConfigs } from './merge-config'
Expand All @@ -8,33 +14,38 @@ import {
SWRConfiguration,
FullConfiguration,
ProviderConfiguration,
Cache
Cache,
CacheProvider
} from '../types'

export const SWRConfigContext = createContext<Partial<FullConfiguration>>({})

const SWRConfig: FC<{
value?: SWRConfiguration &
Partial<ProviderConfiguration> & {
provider?: (cache: Readonly<Cache>) => Cache
}
}> = ({ children, value }) => {
type SWRConfigValue = SWRConfiguration &
Partial<ProviderConfiguration> & {
provider?: CacheProvider<any>
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This does not look correct to me.

export type Cache<T = DefaultProvider, Data = any> = T extends ICache<Data>
  ? T
  : never

export type CacheProvider<Data = any> = (cache: Cache<Data>) => Cache<Data>

CacheProvider<any> = (cache: Cache<any>) => Cache<any> = (cache: any) => any

We need provider to return a Cache here

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I didn't get what do you mean here. Can you rephrase it more specificly?

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Previous

type Provider: (cache: Readonly<Cache>) => Cache
const cache = new Map()
<SWRConfig value={{ provider: () => cache }}>{children}</SWRConfig>
// This will throw type error since { a: foo } does not satisfy the requirement
<SWRConfig value={{ provider: () => {a: foo } }}>{children}</SWRConfig>

Current

type Provider = CacheProvider<any> = (_: any) => any
const cache = new Map()
<SWRConfig value={{ provider: () => cache }}>{children}</SWRConfig>
// This will not throw type error any more
<SWRConfig value={{ provider: () => {a: foo } }}>{children}</SWRConfig>

}

const SWRConfig = ({
value,
children
}: {
value?: SWRConfigValue
children?: React.ReactNode
}): ReactElement | null => {
// Extend parent context values and middleware.
const extendedConfig = mergeConfigs(useContext(SWRConfigContext), value)

const cache = extendedConfig.cache || defaultCache
// Should not use the inherited provider.
const provider = value && value.provider

// Use a lazy initialized state to create the cache on first access.
const [cacheContext] = useState(() =>
provider
? initCache(provider(extendedConfig.cache || defaultCache), value)
: UNDEFINED
provider ? initCache(provider(cache), value) : UNDEFINED
)

// Override the cache if a new provider is given.
if (cacheContext) {
extendedConfig.cache = cacheContext[0]
extendedConfig.cache = cacheContext[0] as Cache
extendedConfig.mutate = cacheContext[1]
}

Expand Down
4 changes: 2 additions & 2 deletions src/utils/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import {
RevalidatorOptions,
Revalidator,
ScopedMutator,
Cache
DefaultProvider
} from '../types'
import { isUndefined, noop, mergeObjects } from './helper'

Expand Down Expand Up @@ -44,7 +44,7 @@ const onErrorRetry = (

// Default cache provider
const [cache, mutate] = initCache(new Map()) as [
Cache<any>,
DefaultProvider,
ScopedMutator<any>,
() => {}
]
Expand Down
6 changes: 4 additions & 2 deletions src/utils/use-swr-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@ import { useContext } from 'react'
import { defaultConfig } from './config'
import { SWRConfigContext } from './config-context'
import { mergeObjects } from './helper'
import { FullConfiguration } from '../types'
import { FullConfiguration, Cache } from '../types'

export const useSWRConfig = (): FullConfiguration => {
export const useSWRConfig = <Provider = Cache>(): FullConfiguration<
Provider
> => {
return mergeObjects(defaultConfig, useContext(SWRConfigContext))
}
45 changes: 45 additions & 0 deletions test/type/provider.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import React from 'react'
import { useEffect } from 'react'
import { DefaultProvider, SWRConfig, useSWRConfig } from 'swr'

export function test1() {
function useCacheClear() {
const { cache: defaultCache } = useSWRConfig()
const { cache } = useSWRConfig<DefaultProvider>()

useEffect(() => {
return () => {
cache.clear() // infer DefaultProvider
defaultCache.clear() // infer DefaultProvider
}
}, [])
return null
}

return useCacheClear
}

export function test2() {
const provider2 = new Map([['k1', 'v1']])
function Inner() {
// infer Map<string, string>
const { cache } = useSWRConfig<typeof provider2>()

useEffect(() => {
return () => cache.clear()
}, [])
return null
}

function useCustomCache2() {
return (
<SWRConfig value={{ provider: () => provider2 }}>
<SWRConfig value={{ provider: (c: typeof provider2) => c }}>
<Inner />
</SWRConfig>
</SWRConfig>
)
}

return useCustomCache2
}