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

fix: only make data and error update as a non-blocking transition #2691

Merged
merged 6 commits into from
Jul 21, 2023
Merged
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
1 change: 0 additions & 1 deletion _internal/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ export { internalMutate } from './utils/mutate'
export { normalize } from './utils/normalize-args'
export { withArgs } from './utils/resolve-args'
export { serialize } from './utils/serialize'
export { useStateWithDeps } from './utils/state'
export { subscribeCallback } from './utils/subscribe-key'
export { getTimestamp } from './utils/timestamp'
export { useSWRConfig } from './utils/use-swr-config'
Expand Down
2 changes: 1 addition & 1 deletion e2e/test/mutate-server-action.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
/* eslint-disable testing-library/prefer-screen-queries */
import { test, expect } from '@playwright/test'

test.skip('mutate-server-action', async ({ page }) => {
test('mutate-server-action', async ({ page }) => {
await page.goto('./mutate-server-action')
await page.getByRole('button', { name: 'mutate' }).click()
await expect(page.getByText('isMutating: true')).toBeVisible()
Expand Down
11 changes: 7 additions & 4 deletions mutation/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { useCallback, useRef } from 'react'
import useSWR, { useSWRConfig } from 'swr'
import type { Middleware, Key } from 'swr/_internal'
import { useStateWithDeps, startTransition } from './state'
import {
serialize,
useStateWithDeps,
withMiddleware,
useIsomorphicLayoutEffect,
UNDEFINED,
Expand All @@ -24,7 +24,6 @@ const mutation = (<Data, Error>() =>
config: SWRMutationConfiguration<Data, Error> = {}
) => {
const { mutate } = useSWRConfig()

const keyRef = useRef(key)
const fetcherRef = useRef(fetcher)
const configRef = useRef(config)
Expand Down Expand Up @@ -76,15 +75,19 @@ const mutation = (<Data, Error>() =>

// If it's reset after the mutation, we don't broadcast any state change.
if (ditchMutationsUntilRef.current <= mutationStartedAt) {
setState({ data, isMutating: false, error: undefined })
startTransition(() =>
promer94 marked this conversation as resolved.
Show resolved Hide resolved
setState({ data, isMutating: false, error: undefined })
)
options.onSuccess?.(data as Data, serializedKey, options)
}
return data
} catch (error) {
// If it's reset after the mutation, we don't broadcast any state change
// or throw because it's discarded.
if (ditchMutationsUntilRef.current <= mutationStartedAt) {
setState({ error: error as Error, isMutating: false })
startTransition(() =>
setState({ error: error as Error, isMutating: false })
)
options.onError?.(error as Error, serializedKey, options)
if (options.throwOnError) {
throw error as Error
Expand Down
56 changes: 28 additions & 28 deletions _internal/src/utils/state.ts → mutation/src/state.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,13 @@
import type { MutableRefObject } from 'react'
import type { MutableRefObject, TransitionFunction } from 'react'
import React, { useRef, useCallback, useState } from 'react'
import { useIsomorphicLayoutEffect, IS_REACT_LEGACY } from './env'
import { useIsomorphicLayoutEffect, IS_REACT_LEGACY } from 'swr/_internal'

export const startTransition: (scope: TransitionFunction) => void =
IS_REACT_LEGACY
? React.startTransition
: cb => {
cb()
}

/**
* An implementation of state with dependency-tracking.
Expand All @@ -12,7 +19,7 @@ export const useStateWithDeps = <S = any>(
Record<keyof S, boolean>,
(payload: Partial<S>) => void
] => {
const rerender = useState<Record<string, unknown>>({})[1]
const [, rerender] = useState<Record<string, unknown>>({})
const unmountedRef = useRef(false)
const stateRef = useRef(state)

Expand Down Expand Up @@ -43,37 +50,30 @@ export const useStateWithDeps = <S = any>(
* })
* ```
*/
const setState = useCallback(
(payload: Partial<S>) => {
let shouldRerender = false
const setState = useCallback((payload: Partial<S>) => {
let shouldRerender = false

const currentState = stateRef.current
for (const _ in payload) {
const k = _ as keyof S
const currentState = stateRef.current
for (const _ in payload) {
const k = _ as keyof S

// If the property has changed, update the state and mark rerender as
// needed.
if (currentState[k] !== payload[k]) {
currentState[k] = payload[k]
// If the property has changed, update the state and mark rerender as
// needed.
if (currentState[k] !== payload[k]) {
currentState[k] = payload[k]

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

if (shouldRerender && !unmountedRef.current) {
if (IS_REACT_LEGACY) {
rerender({})
} else {
;(React as any).startTransition(() => rerender({}))
}
}
},
[rerender]
)
if (shouldRerender && !unmountedRef.current) {
rerender({})
}
}, [])

useIsomorphicLayoutEffect(() => {
unmountedRef.current = false
Expand Down