File tree Expand file tree Collapse file tree 3 files changed +42
-0
lines changed
packages/use-query-params/src Expand file tree Collapse file tree 3 files changed +42
-0
lines changed Original file line number Diff line number Diff line change @@ -448,5 +448,35 @@ export function testSpec(renderWithRouter: any) {
448448 ) ;
449449 expect ( numRenders ) . toBe ( 2 ) ;
450450 } ) ;
451+
452+ it ( 'doesnt update when the search string is the same' , async ( ) => {
453+ let numRenders = 0 ;
454+ const TestComponent = ( ) => {
455+ const [ foo , setFoo ] = useQueryParam ( 'foo' ) ;
456+
457+ numRenders += 1 ;
458+ return (
459+ < div >
460+ { JSON . stringify ( { foo } ) }
461+ < button
462+ onClick = { ( ) => {
463+ setFoo ( 'foo1' ) ;
464+ } }
465+ >
466+ Change
467+ </ button >
468+ </ div >
469+ ) ;
470+ } ;
471+ const { queryByText, getByText } = renderWithRouter (
472+ < TestComponent /> ,
473+ '?foo=foo1'
474+ ) ;
475+
476+ expect ( queryByText ( / { " f o o " : " f o o 1 " } / ) ) . toBeTruthy ( ) ;
477+ getByText ( / C h a n g e / ) . click ( ) ;
478+ await waitFor ( ( ) => expect ( queryByText ( / { " f o o " : " f o o 1 " } / ) ) . toBeTruthy ( ) ) ;
479+ expect ( numRenders ) . toBe ( 1 ) ;
480+ } ) ;
451481 } ) ;
452482}
Original file line number Diff line number Diff line change @@ -14,6 +14,7 @@ export const defaultOptions: QueryParamOptionsWithRequired = {
1414 includeAllParams : false ,
1515 removeDefaultsFromUrl : false ,
1616 enableBatching : false ,
17+ skipUpdateWhenNoChange : true ,
1718} ;
1819
1920export interface QueryParamOptions {
@@ -22,6 +23,8 @@ export interface QueryParamOptions {
2223 updateType ?: UrlUpdateType ;
2324 includeKnownParams ?: boolean ;
2425 includeAllParams ?: boolean ;
26+ /** whether sets that result in no change to the location search string should be ignored (default: true) */
27+ skipUpdateWhenNoChange ?: boolean ;
2528 params ?: QueryParamConfigMap ;
2629
2730 /** when a value equals its default, do not encode it in the URL when updating */
Original file line number Diff line number Diff line change @@ -155,6 +155,7 @@ export function enqueueUpdate(
155155 scheduleTask ( ( ) => {
156156 const updates = updateQueue . slice ( ) ;
157157 updateQueue . length = 0 ;
158+ const initialSearchString = updates [ 0 ] . currentSearchString ;
158159
159160 let searchString : string | undefined ;
160161 for ( let i = 0 ; i < updates . length ; ++ i ) {
@@ -165,6 +166,14 @@ export function enqueueUpdate(
165166 searchString = getUpdatedSearchString ( modifiedUpdate ) ;
166167 }
167168
169+ // do not update unnecessarily #234
170+ if (
171+ args . options . skipUpdateWhenNoChange &&
172+ searchString === initialSearchString
173+ ) {
174+ return ;
175+ }
176+
168177 updateSearchString ( {
169178 searchString : searchString ?? '' ,
170179 adapter : updates [ updates . length - 1 ] . adapter ,
You can’t perform that action at this time.
0 commit comments