Skip to content

Commit

Permalink
compose: Add types to useWarnOnChange
Browse files Browse the repository at this point in the history
  • Loading branch information
sarayourfriend committed May 27, 2021
1 parent c2d96df commit 5eccce6
Show file tree
Hide file tree
Showing 3 changed files with 9 additions and 4 deletions.
2 changes: 1 addition & 1 deletion packages/compose/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -485,7 +485,7 @@ function MyComponent(props) {

_Parameters_

- _object_ `Object`: Object which changes to compare.
- _object_ `object`: Object which changes to compare.
- _prefix_ `string`: Just a prefix to show when console logging.

<a name="withGlobalEvents" href="#withGlobalEvents">#</a> **withGlobalEvents**
Expand Down
10 changes: 7 additions & 3 deletions packages/compose/src/hooks/use-warn-on-change/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@
*/
import usePrevious from '../use-previous';

// Disable reason: Object and object are distinctly different types in TypeScript and we mean the lowercase object in thise case
// but eslint wants to force us to use `Object`. See https://stackoverflow.com/questions/49464634/difference-between-object-and-object-in-typescript
/* eslint-disable jsdoc/check-types */
/**
* Hook that performs a shallow comparison between the preview value of an object
* and the new one, if there's a difference, it prints it to the console.
Expand All @@ -18,19 +21,20 @@ import usePrevious from '../use-previous';
* }
* ```
*
* @param {Object} object Object which changes to compare.
* @param {object} object Object which changes to compare.
* @param {string} prefix Just a prefix to show when console logging.
*/
function useWarnOnChange( object, prefix = 'Change detection' ) {
const previousValues = usePrevious( object );

Object.entries( previousValues ?? [] ).forEach( ( [ key, value ] ) => {
if ( value !== object[ key ] ) {
if ( value !== object[ /** @type {keyof typeof object} */ ( key ) ] ) {
// eslint-disable-next-line no-console
console.warn(
`${ prefix }: ${ key } key changed:`,
value,
object[ key ]
object[ /** @type {keyof typeof object} */ ( key ) ]
/* eslint-enable jsdoc/check-types */
);
}
} );
Expand Down
1 change: 1 addition & 0 deletions packages/compose/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
"src/hooks/use-reduced-motion/**/*",
"src/hooks/use-merge-refs/**/*",
"src/hooks/use-resize-observer/**/*",
"src/hooks/use-warn-on-change/**/*",
"src/utils/**/*"
]
}

0 comments on commit 5eccce6

Please sign in to comment.