-
Notifications
You must be signed in to change notification settings - Fork 900
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
refactor(hooks): Pulling out useData (#7325)
- Loading branch information
1 parent
0fbafe6
commit 598b5b3
Showing
3 changed files
with
29 additions
and
14 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1 +1,2 @@ | ||
export * from './useLatestPromise'; | ||
export * from './useData'; |
23 changes: 23 additions & 0 deletions
23
app/scripts/modules/core/src/presentation/hooks/useData.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,23 @@ | ||
import { IPromise } from 'angular'; | ||
import { $q } from 'ngimport'; | ||
import { isNil } from 'lodash'; | ||
|
||
import { useLatestPromise, IUseLatestPromiseResult } from './useLatestPromise'; | ||
|
||
/** | ||
* A react hook which invokes a promise returning callback whenever any of its dependencies changes. | ||
* Returns the provided default value whenever any dependency is null or undefined | ||
* | ||
* This can be useful when fetching data based on a users keyboard input, for example. | ||
* This behavior is similar to RxJS switchMap. | ||
* | ||
* @param callback the callback to be invoked whenever dependencies change | ||
* @param defaultValue the default value to return when any dependencies are null or undefined | ||
* @param deps array of dependencies, which (when changed) cause the callback to be invoked again | ||
* @returns an object with the result and current status of the promise | ||
*/ | ||
export function useData<T>(callback: () => IPromise<T>, defaultValue: T, deps: any[]): IUseLatestPromiseResult<T> { | ||
const anyDepsMissing = deps.some(dep => isNil(dep)); | ||
const defaultValueCallback = () => $q.resolve(defaultValue); | ||
return useLatestPromise(anyDepsMissing ? defaultValueCallback : callback, deps); | ||
} |