-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
use
useSerializedStableValue
for value comparison (#1533)
Co-authored-by: Matt Sutkowski <msutkowski@gmail.com>
- Loading branch information
1 parent
18ef51d
commit a44511e
Showing
5 changed files
with
65 additions
and
13 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
31 changes: 31 additions & 0 deletions
31
packages/toolkit/src/query/react/useSerializedStableValue.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,31 @@ | ||
import { useEffect, useRef, useMemo } from 'react' | ||
import type { SerializeQueryArgs } from '@reduxjs/toolkit/dist/query/defaultSerializeQueryArgs' | ||
import type { EndpointDefinition } from '@reduxjs/toolkit/dist/query/endpointDefinitions' | ||
|
||
export function useStableQueryArgs<T>( | ||
queryArgs: T, | ||
serialize: SerializeQueryArgs<any>, | ||
endpointDefinition: EndpointDefinition<any, any, any, any>, | ||
endpointName: string | ||
) { | ||
const incoming = useMemo( | ||
() => ({ | ||
queryArgs, | ||
serialized: | ||
typeof queryArgs == 'object' | ||
? serialize({ queryArgs, endpointDefinition, endpointName }) | ||
: queryArgs, | ||
}), | ||
[queryArgs, serialize, endpointDefinition, endpointName] | ||
) | ||
const cache = useRef(incoming) | ||
useEffect(() => { | ||
if (cache.current.serialized !== incoming.serialized) { | ||
cache.current = incoming | ||
} | ||
}, [incoming]) | ||
|
||
return cache.current.serialized === incoming.serialized | ||
? cache.current.queryArgs | ||
: queryArgs | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters