Skip to content

Commit 41443ce

Browse files
dinwwwhclaude
andauthored
fix(next): use latest interceptors in useServerFunction execute (#2388)
## Problem `useServerFunction` memoized `execute` with `useCallback(..., [fn, ...toArray(options.interceptors)])`. The dependency array's length changed with the number of interceptors. React only compares deps up to the shorter length (it just logs a dev warning), so when interceptors were added or removed at the end, `execute` was not recreated and kept running the old ones: - `[a]` → `[a, b]`: `b` never runs - `undefined` → `[a]`: `a` never runs - `[a, b]` → `[a]`: the removed `b` still runs ## Fix The latest `options.interceptors` are stored in a ref that is updated on every render. `execute` reads the ref, so its deps are just `[fn]`. As a result `execute` always uses the current interceptors and keeps the same identity across renders. Before, it was recreated on every render whenever interceptors were passed inline, which is what the docs show. `useOptimisticServerFunction` no longer wraps its `onStart` interceptor in `useCallback`. That wrapper was only there to keep the old spread deps stable. I searched `packages/next`, `packages/tanstack-query`, `packages/swr` and `packages/pinia-colada` for the same spread-into-deps pattern. This was the only place it appeared. ## Tests Added one `renderHook` + `rerender` test that walks `undefined → [a, b] → [a] → undefined`. After each rerender it checks that `execute` keeps the same identity and that only the current interceptors run. The test fails on the old code and passes with the fix. `pnpm vitest run packages/next`, `pnpm type:check` and `pnpm lint` all pass. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01VVaw7RfVeu6u8YEbwh664n --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 9505dac commit 41443ce

3 files changed

Lines changed: 50 additions & 5 deletions

File tree

‎packages/next/src/hooks/optimistic-server-function.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import type { AnyORPCErrorJSON } from '@orpc/client'
22
import type { ServerFunction, ServerFunctionError } from '../server-function'
33
import type { UserSeverFunctionOptions, UseServerFunctionResult } from './server-function'
44
import { onStart, toArray } from '@orpc/shared'
5-
import { useCallback, useMemo, useOptimistic } from 'react'
5+
import { useMemo, useOptimistic } from 'react'
66
import { useServerFunction } from './server-function'
77

88
export interface UseOptimisticServerFunctionOptions<TInput, TOutput, TError, TOptimisticState> extends
@@ -30,9 +30,9 @@ export function useOptimisticServerFunction<TInput, TOutput, TError extends AnyO
3030
const state = useServerFunction(fn, {
3131
...options,
3232
interceptors: [
33-
useCallback(onStart(({ input }) => {
33+
onStart(({ input }) => {
3434
addOptimistic(input)
35-
}), [addOptimistic]),
35+
}),
3636
...toArray(options.interceptors),
3737
],
3838
})

‎packages/next/src/hooks/server-function.test.tsx‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -221,6 +221,48 @@ describe('useServerFunction', () => {
221221
})
222222
})
223223

224+
it('interceptors change between renders', async () => {
225+
const a = vi.fn(({ next }) => next())
226+
const b = vi.fn(({ next }) => next())
227+
228+
const { result, rerender } = renderHook(
229+
({ interceptors }) => useServerFunction(fn, { interceptors }),
230+
{ initialProps: { interceptors: undefined as any[] | undefined } },
231+
)
232+
233+
const execute = result.current.execute
234+
235+
rerender({ interceptors: [a, b] })
236+
expect(result.current.execute).toBe(execute)
237+
238+
await act(async () => {
239+
await result.current.execute({ input: 123 })
240+
})
241+
242+
expect(a).toHaveBeenCalledTimes(1)
243+
expect(b).toHaveBeenCalledTimes(1)
244+
245+
rerender({ interceptors: [a] })
246+
expect(result.current.execute).toBe(execute)
247+
248+
await act(async () => {
249+
await result.current.execute({ input: 123 })
250+
})
251+
252+
expect(a).toHaveBeenCalledTimes(2)
253+
expect(b).toHaveBeenCalledTimes(1)
254+
255+
rerender({ interceptors: undefined })
256+
expect(result.current.execute).toBe(execute)
257+
258+
await act(async () => {
259+
await result.current.execute({ input: 123 })
260+
})
261+
262+
expect(a).toHaveBeenCalledTimes(2)
263+
expect(b).toHaveBeenCalledTimes(1)
264+
})
265+
224266
it('multiple execute calls', async () => {
225267
const { result } = renderHook(() => useServerFunction(fn))
226268

‎packages/next/src/hooks/server-function.ts‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -120,6 +120,9 @@ export function useServerFunction<TInput, TOutput, TError extends AnyORPCErrorJS
120120
const [input, setInput] = useState<TInput | undefined>(undefined)
121121
const [isPending, startTransition] = useTransition()
122122

123+
const interceptorsRef = useRef(options.interceptors)
124+
interceptorsRef.current = options.interceptors
125+
123126
const reset = useCallback(() => {
124127
executedAtRef.current = undefined
125128
setInput(undefined)
@@ -135,7 +138,7 @@ export function useServerFunction<TInput, TOutput, TError extends AnyORPCErrorJS
135138
return new Promise((resolve) => {
136139
startTransition(async () => {
137140
const result = await safe(intercept(
138-
[...toArray(options.interceptors), ...toArray(executeOptions.interceptors)],
141+
[...toArray(interceptorsRef.current), ...toArray(executeOptions.interceptors)],
139142
{ input: input as TInput },
140143
async ({ input }) => fn(input).then(([error, data]) => {
141144
if (error) {
@@ -164,7 +167,7 @@ export function useServerFunction<TInput, TOutput, TError extends AnyORPCErrorJS
164167
resolve(result)
165168
})
166169
})
167-
}, [fn, ...toArray(options.interceptors)])
170+
}, [fn])
168171

169172
const result = useMemo(() => {
170173
const currentState = isPending && executedAtRef.current !== undefined

0 commit comments

Comments
 (0)