Skip to content

Chore: code refactoring for swr/infinite #1452

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

Merged
merged 2 commits into from
Sep 13, 2021
Merged
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
17 changes: 7 additions & 10 deletions infinite/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,37 +31,37 @@ export const infinite = ((<Data, Error>(useSWRNext: SWRHook) => (
fn: Fetcher<Data> | null,
config: typeof SWRConfig.default & SWRInfiniteConfiguration<Data, Error>
): SWRInfiniteResponse<Data, Error> => {
const rerender = useState({})[1]
const didMountRef = useRef<boolean>(false)
const dataRef = useRef<Data[]>()

const {
cache,
initialSize = 1,
revalidateAll = false,
persistSize = false
} = config

// get the serialized key of the first page
// The serialized key of the first page.
let firstPageKey: string | null = null
try {
firstPageKey = getFirstPageKey(getKey)
} catch (err) {
// not ready
}

const rerender = useState({})[1]

// We use cache to pass extra info (context) to fetcher so it can be globally
// shared. The key of the context data is based on the first page key.
let contextCacheKey: string | null = null
if (firstPageKey) {
contextCacheKey = '$ctx$' + firstPageKey
}

// Page size is also cached to share the page data between hooks with the
// same key.
let pageSizeCacheKey: string | null = null

if (firstPageKey) {
contextCacheKey = '$ctx$' + firstPageKey
pageSizeCacheKey = '$len$' + firstPageKey
}
const didMountRef = useRef<boolean>(false)

const resolvePageSize = useCallback((): number => {
const cachedPageSize = cache.get(pageSizeCacheKey)
Expand Down Expand Up @@ -92,9 +92,6 @@ export const infinite = ((<Data, Error>(useSWRNext: SWRHook) => (
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [firstPageKey])

// keep the data inside a ref
const dataRef = useRef<Data[]>()

// Actual SWR hook to load all pages in one fetcher.
const swr = useSWRNext<Data[], Error>(
firstPageKey ? INFINITE_PREFIX + firstPageKey : null,
Expand Down