-
Notifications
You must be signed in to change notification settings - Fork 2.7k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Use useNormalizedOptions for useLazyQuery as well as useQuery.
- Loading branch information
Showing
4 changed files
with
58 additions
and
37 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,40 @@ | ||
import { useRef } from "react"; | ||
import equal from "@wry/equality"; | ||
|
||
import { | ||
QueryHookOptions, | ||
LazyQueryHookOptions, | ||
} from "../types/types"; | ||
|
||
// I would have made this function a method of the InternalState class, but it | ||
// needs to run before we get the client from useApolloClient in the useQuery | ||
// function above, just in case the options function returns options.client as | ||
// an override for the ApolloClient instance provided by React context. | ||
export function useNormalizedOptions< | ||
TOptions extends | ||
| QueryHookOptions<any, any> | ||
| LazyQueryHookOptions<any, any> | ||
>( | ||
optionsOrFunction?: | ||
| TOptions | ||
| ((prevOptions: TOptions) => TOptions) | ||
): TOptions { | ||
const optionsRef = useRef<TOptions>(); | ||
let options: TOptions = optionsRef.current || Object.create(null); | ||
|
||
if (typeof optionsOrFunction === "function") { | ||
const newOptions = optionsOrFunction(options); | ||
if (newOptions !== options) { | ||
Object.assign(options, newOptions, newOptions.variables && { | ||
variables: { | ||
...options.variables, | ||
...newOptions.variables, | ||
}, | ||
}); | ||
} | ||
} else if (optionsOrFunction && !equal(optionsOrFunction, options)) { | ||
options = optionsOrFunction; | ||
} | ||
|
||
return optionsRef.current = options; | ||
} |
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
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