Skip to content

read cache during render #794

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 23 commits into from
Mar 28, 2021
Merged
Show file tree
Hide file tree
Changes from 22 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
6 changes: 4 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -62,8 +62,10 @@
"jest": "25.5.4",
"lint-staged": "8.2.1",
"prettier": "1.18.2",
"react": "16.11.0",
"react-dom": "16.11.0",
"react": "17.0.1",
"react-dom": "17.0.1",
"react-dom-experimental": "npm:react-dom@experimental",
"react-experimental": "npm:react@experimental",
"ts-jest": "25.5.1",
"typescript": "3.6.4"
},
Expand Down
87 changes: 87 additions & 0 deletions src/state.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
import { useRef, useCallback, useState, MutableRefObject } from 'react'

import { useIsomorphicLayoutEffect } from './env'
import { State } from './types'

type StateKeys = keyof State<any, any>
type StateDeps = Record<StateKeys, boolean>

/**
* An implementation of state with dependency-tracking.
*/
export default function useStateWithDeps<Data, Error, S = State<Data, Error>>(
state: S,
unmountedRef: MutableRefObject<boolean>
): [
MutableRefObject<S>,
MutableRefObject<Record<StateKeys, boolean>>,
(payload: S) => void
] {
const rerender = useState<object>({})[1]

const stateRef = useRef(state)
useIsomorphicLayoutEffect(() => {
stateRef.current = state
})

// If a state property (data, error or isValidating) is accessed by the render
// function, we mark the property as a dependency so if it is updated again
// in the future, we trigger a rerender.
// This is also known as dependency-tracking.
const stateDependenciesRef = useRef<StateDeps>({
data: false,
error: false,
isValidating: false
})

/**
* @param payload To change stateRef, pass the values explicitly to setState:
* @example
* ```js
* setState({
* isValidating: false
* data: newData // set data to newData
* error: undefined // set error to undefined
* })
*
* setState({
* isValidating: false
* data: undefined // set data to undefined
* error: err // set error to err
* })
* ```
*/
const setState = useCallback(
(payload: S) => {
let shouldRerender = false

for (const _ of Object.keys(payload)) {
// Type casting to work around the `for...in` loop
// https://github.com/Microsoft/TypeScript/issues/3500
const k = _ as keyof S & StateKeys

// If the property hasn't changed, skip
if (stateRef.current[k] === payload[k]) {
continue
}

stateRef.current[k] = payload[k]

// If the property is accessed by the component, a rerender should be
// triggered.
if (stateDependenciesRef.current[k]) {
shouldRerender = true
}
}

if (shouldRerender && !unmountedRef.current) {
rerender({})
}
},
// config.suspense isn't allowed to change during the lifecycle
// eslint-disable-next-line react-hooks/exhaustive-deps
[]
)

return [stateRef, stateDependenciesRef, setState]
}
13 changes: 8 additions & 5 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,22 +25,22 @@ export interface Configuration<
isPaused: () => boolean
onLoadingSlow: (
key: string,
config: Readonly<Required<Configuration<Data, Error>>>
config: Readonly<Configuration<Data, Error>>
) => void
onSuccess: (
data: Data,
key: string,
config: Readonly<Required<Configuration<Data, Error>>>
config: Readonly<Configuration<Data, Error>>
) => void
onError: (
err: Error,
key: string,
config: Readonly<Required<Configuration<Data, Error>>>
config: Readonly<Configuration<Data, Error>>
) => void
onErrorRetry: (
err: Error,
key: string,
config: Readonly<Required<Configuration<Data, Error>>>,
config: Readonly<Configuration<Data, Error>>,
revalidate: Revalidator,
revalidateOpts: Required<RevalidatorOptions>
) => void
Expand Down Expand Up @@ -77,7 +77,7 @@ export type Broadcaster<Data = any, Error = any> = (
isValidating?: boolean
) => void

export type Action<Data, Error> = {
export type State<Data, Error> = {
data?: Data
error?: Error
isValidating?: boolean
Expand Down Expand Up @@ -123,6 +123,9 @@ export type responseInterface<Data, Error> = {
export interface SWRResponse<Data, Error> {
data?: Data
error?: Error
/**
* @deprecated `revalidate` is deprecated, please use `mutate()` for the same purpose.
*/
revalidate: () => Promise<boolean>
mutate: (
data?: Data | Promise<Data> | MutatorCallback<Data>,
Expand Down
Loading