Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: new hook useValidator #101

Merged
merged 3 commits into from
Jun 2, 2021
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,13 @@ module.exports = {
'react/prop-types': 'off',
},
},
{
files: ['src/**/__tests__/*.ts'],
rules: {
'@typescript-eslint/no-unused-vars': 'off',
'@typescript-eslint/no-explicit-any': 'off',
},
},
{
files: ['*.md'],
extends: ['plugin:mdx/recommended', 'prettier'],
Expand Down
1 change: 0 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,3 @@ node_modules
/cjs
/esm
/esnext
/types
4 changes: 2 additions & 2 deletions .storybook/main.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
module.exports = {
stories: ['../src/**/__docs__/*.mdx'],
stories: ['../src/**/__docs__/*.mdx', '../src/**/__docs__/*.tsx'],
addons: [
'@storybook/addon-links',
{
name: '@storybook/addon-essentials',
options: {
backgrounds: false,
},
},
'@storybook/addon-docs',
],
reactOptions: {
fastRefresh: true,
Expand Down
1 change: 1 addition & 0 deletions .storybook/preview.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
export const parameters = {
layout: 'centered',
viewMode: 'docs',
};
7 changes: 4 additions & 3 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -59,9 +59,10 @@ first.
4ex: `src/useFirstMountState/__docs__/story.mdx`.
- Docs are built with storybook, to help you during writing docs - start webserver
with `yarn storybook:watch`.
- Components representing hook functionality should be placed next to story file, within
`__docs__` folder.
4ex: `src/useFirstMountState/__docs__/example.tsx`.
- Components representing hook functionality should be placed in `example.stories.tsx` within
`__docs__` folder. In case file name will be missing `.stories.tsx` part - code preview won't
work.
4ex: `src/useFirstMountState/__docs__/example.stories.tsx`.
- Preferred format to write the docs is
MDX. [Read more about storybook docs](https://storybook.js.org/docs/react/writing-docs/introduction).
5. Add docs link and hook summary to the `README.md`.
Expand Down
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,8 @@ import { useMountEffect } from "@react-hookz/web/esnext";
— Like `useState`, but its state setter is guarded against sets on unmounted component.
- [**`useToggle`**](https://react-hookz.github.io/web/?path=/docs/state-usetoggle)
— Like `useState`, but can only become `true` or `false`.
- [**`useValidator`**](https://react-hookz.github.io/web/?path=/docs/state-usevalidator)
— Performs validation when any of provided dependencies has changed.

- #### Navigator

Expand Down
1 change: 0 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,6 @@
"eslint-plugin-prettier": "^3.4.0",
"eslint-plugin-react": "^7.23.2",
"eslint-plugin-react-hooks": "^4.2.0",
"globby": "^11.0.3",
"husky": "^4.3.8",
"jest": "^26.6.3",
"jest-github-actions-reporter": "^1.0.3",
Expand Down
8 changes: 8 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,3 +44,11 @@ export { useMeasure } from './useMeasure/useMeasure';

// Dom
export { useDocumentTitle, IUseDocumentTitleOptions } from './useDocumentTitle/useDocumentTitle';

export {
useValidator,
IValidatorImmediate,
IValidatorDeferred,
IValidator,
IValidityState,
} from './useValidator/useValidator';
2 changes: 1 addition & 1 deletion src/useConditionalEffect/__docs__/story.mdx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Canvas, Meta, Story } from '@storybook/addon-docs/blocks';
import { Example } from './example';
import { Example } from './example.stories';

<Meta title="Lifecycle/useConditionalEffect" component={Example} />

Expand Down
2 changes: 1 addition & 1 deletion src/useConditionalUpdateEffect/__docs__/story.mdx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Canvas, Meta, Story } from '@storybook/addon-docs/blocks';
import { Example } from './example';
import { Example } from './example.stories';

<Meta title="Lifecycle/useConditionalUpdateEffect" component={Example} />

Expand Down
2 changes: 1 addition & 1 deletion src/useDebounceCallback/__docs__/story.mdx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Canvas, Meta, Story } from '@storybook/addon-docs/blocks';
import { Example } from './example';
import { Example } from './example.stories';

<Meta title="Callback/useDebounceCallback" component={Example} />

Expand Down
16 changes: 16 additions & 0 deletions src/useDebounceCallback/__tests__/dom.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,22 @@ describe('useDebounceCallback', () => {
expect(result.error).toBeUndefined();
});

it('should return function same length and wrapped name', () => {
let { result } = renderHook(() =>
useDebounceCallback((_a: any, _b: any, _c: any) => {}, 200, [])
);

expect(result.current.length).toBe(3);
expect(result.current.name).toBe(`anonymous__debounced__200`);

function testFn(_a: any, _b: any, _c: any) {}

result = renderHook(() => useDebounceCallback(testFn, 100, [])).result;

expect(result.current.length).toBe(3);
expect(result.current.name).toBe(`testFn__debounced__100`);
});

it('should return new callback if delay is changed', () => {
const { result, rerender } = renderHook(
({ delay }) => useDebounceCallback(() => {}, delay, []),
Expand Down
16 changes: 12 additions & 4 deletions src/useDebounceCallback/useDebounceCallback.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,18 +14,26 @@ export function useDebounceCallback<T extends (...args: any[]) => any>(
deps: DependencyList
): (...args: Parameters<T>) => void {
const timeout = useRef<ReturnType<typeof setTimeout>>();

return useMemo(
() =>
(...args: Parameters<T>): void => {
() => {
// eslint-disable-next-line func-names
const debounced = function (...args: Parameters<T>): void {
if (timeout.current) clearTimeout(timeout.current);

timeout.current = setTimeout(() => {
timeout.current = undefined;

cb(...args);
}, delay);
},
};

Object.defineProperties(debounced, {
length: { value: cb.length },
name: { value: `${cb.name || 'anonymous'}__debounced__${delay}` },
});

return debounced;
},
// eslint-disable-next-line react-hooks/exhaustive-deps
[delay, ...deps]
);
Expand Down
2 changes: 1 addition & 1 deletion src/useDocumentTitle/__docs__/story.mdx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Canvas, Meta, Story } from '@storybook/addon-docs/blocks';
import { Example } from './example';
import { Example } from './example.stories';

<Meta title="Dom/useDocumentTitle" component={Example} />

Expand Down
2 changes: 1 addition & 1 deletion src/useFirstMountState/__docs__/story.mdx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Canvas, Meta, Story, Typeset } from '@storybook/addon-docs/blocks';
import { Example } from './example';
import { Example } from './example.stories';

<Meta title="Lifecycle/useFirstMountState" component={Example} />

Expand Down
2 changes: 1 addition & 1 deletion src/useIsMounted/__docs__/story.mdx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Canvas, Meta, Story } from '@storybook/addon-docs/blocks';
import { Example } from './example';
import { Example } from './example.stories';

<Meta title="Lifecycle/useIsMounted" component={Example} />

Expand Down
2 changes: 1 addition & 1 deletion src/useLocalStorageValue/__docs__/story.mdx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Example } from './example';
import { Example } from './example.stories';
import { ArgsTable, Canvas, Meta, Story } from '@storybook/addon-docs/blocks';

<Meta title="Side-effect/useLocalStorageValue" component={Example} />
Expand Down
2 changes: 1 addition & 1 deletion src/useMeasure/__docs__/story.mdx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Canvas, Meta, Story } from '@storybook/addon-docs/blocks';
import { Example } from './example';
import { Example } from './example.stories';

<Meta title="Sensor/useMeasure" />

Expand Down
2 changes: 1 addition & 1 deletion src/useMediatedState/__docs__/story.mdx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Canvas, Meta, Story } from '@storybook/addon-docs/blocks';
import { Example } from './example';
import { Example } from './example.stories';

<Meta title="State/useMediatedState" component={Example} />

Expand Down
2 changes: 1 addition & 1 deletion src/useMountEffect/__docs__/story.mdx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Canvas, Meta, Story } from '@storybook/addon-docs/blocks';
import { Example } from './example';
import { Example } from './example.stories';

<Meta title="Lifecycle/useMountEffect" component={Example} />

Expand Down
2 changes: 1 addition & 1 deletion src/useNetworkState/__docs__/story.mdx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Example } from './example';
import { Example } from './example.stories';
import { Canvas, Meta, Story } from '@storybook/addon-docs/blocks';

<Meta title={'Navigator/useNetwork'} component={Example} />
Expand Down
2 changes: 1 addition & 1 deletion src/usePrevious/__docs__/story.mdx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Canvas, Meta, Story } from '@storybook/addon-docs/blocks';
import { Example } from './example';
import { Example } from './example.stories';

<Meta title="State/usePrevious" component={Example} />

Expand Down
2 changes: 1 addition & 1 deletion src/useRafCallback/__docs__/story.mdx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Canvas, Meta, Story } from '@storybook/addon-docs/blocks';
import { Example } from './example';
import { Example } from './example.stories';

<Meta title="Callback/useRafCallback" component={Example} />

Expand Down
16 changes: 15 additions & 1 deletion src/useRafCallback/__tests__/dom.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { renderHook } from '@testing-library/react-hooks/dom';
import { useRafCallback } from '../..';
import { useDebounceCallback, useRafCallback } from '../..';

describe('useRafCallback', () => {
const raf = global.requestAnimationFrame;
Expand Down Expand Up @@ -27,6 +27,20 @@ describe('useRafCallback', () => {
renderHook(() => useRafCallback(() => {}));
});

it('should return function same length and wrapped name', () => {
let { result } = renderHook(() => useRafCallback((_a: any, _b: any, _c: any) => {}));

expect(result.current[0].length).toBe(3);
expect(result.current[0].name).toBe(`anonymous__raf`);

function testFn(_a: any, _b: any, _c: any) {}

result = renderHook(() => useRafCallback(testFn)).result;

expect(result.current[0].length).toBe(3);
expect(result.current[0].name).toBe(`testFn__raf`);
});

it('should return array of functions', () => {
const { result } = renderHook(() => useRafCallback(() => {}));

Expand Down
24 changes: 17 additions & 7 deletions src/useRafCallback/useRafCallback.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useCallback, useRef } from 'react';
import { useCallback, useMemo, useRef } from 'react';
import { useSyncedRef } from '../useSyncedRef/useSyncedRef';
import { isBrowser } from '../util/const';
import { useUnmountEffect } from '../useUnmountEffect/useUnmountEffect';
Expand Down Expand Up @@ -29,17 +29,27 @@ export function useRafCallback<T extends (...args: any[]) => any>(
useUnmountEffect(cancel);

return [
useCallback((...args) => {
if (!isBrowser) return;
useMemo(() => {
const wrapped = (...args: Parameters<T>) => {
if (!isBrowser) return;

cancel();
cancel();

frame.current = requestAnimationFrame(() => {
cbRef.current(...args);
frame.current = 0;
frame.current = requestAnimationFrame(() => {
cbRef.current(...args);
frame.current = 0;
});
};

Object.defineProperties(wrapped, {
length: { value: cb.length },
name: { value: `${cb.name || 'anonymous'}__raf` },
});

return wrapped;
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []),

cancel,
];
}
2 changes: 1 addition & 1 deletion src/useRerender/__docs__/story.mdx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Canvas, Meta, Story } from '@storybook/addon-docs/blocks';
import { Example } from './example';
import { Example } from './example.stories';

<Meta title="Lifecycle/useRerender" component={Example} />

Expand Down
2 changes: 1 addition & 1 deletion src/useResizeObserver/__docs__/story.mdx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Canvas, Meta, Story } from '@storybook/addon-docs/blocks';
import { Example, ExampleDebounced } from './example';
import { Example, ExampleDebounced } from './example.stories';

<Meta title="Sensor/useResizeObserver" />

Expand Down
2 changes: 1 addition & 1 deletion src/useSessionStorageValue/__docs__/story.mdx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Example } from './example';
import { Example } from './example.stories';
import { ArgsTable, Canvas, Meta, Story } from '@storybook/addon-docs/blocks';

<Meta title="Side-effect/useSessionStorageValue" component={Example} />
Expand Down
2 changes: 1 addition & 1 deletion src/useSyncedRef/__docs__/story.mdx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Canvas, Meta, Story } from '@storybook/addon-docs/blocks';
import { Example } from './example';
import { Example } from './example.stories';

<Meta title="Miscellaneous/useSyncedRef" component={Example} />

Expand Down
2 changes: 1 addition & 1 deletion src/useToggle/__docs__/story.mdx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Canvas, Meta, Story } from '@storybook/addon-docs/blocks';
import { Example } from './example';
import { Example } from './example.stories';

<Meta title="State/useToggle" component={Example} />

Expand Down
2 changes: 1 addition & 1 deletion src/useUnmountEffect/__docs__/story.mdx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Canvas, Meta, Story } from '@storybook/addon-docs/blocks';
import { Example } from './example';
import { Example } from './example.stories';

<Meta title="Lifecycle/useUnmountEffect" component={Example} />

Expand Down
2 changes: 1 addition & 1 deletion src/useUpdateEffect/__docs__/story.mdx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Canvas, Meta, Story } from '@storybook/addon-docs/blocks';
import { Example } from './example';
import { Example } from './example.stories';

<Meta title="Lifecycle/useUpdateEffect" component={Example} />

Expand Down
48 changes: 48 additions & 0 deletions src/useValidator/__docs__/example.stories.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import * as React from 'react';
import { useState } from 'react';
import { IValidatorDeferred, useDebounceCallback, useValidator } from '../..';

export const ExampleStories: React.FC = () => {
const [text, setText] = useState('');

// as deferred validator is unable to infer the type of validity
// state - we should define it ourself
type ITextValidityState = { isValid: boolean | undefined; error: Error | undefined };

// debounced callback is deferred callback so we should use deferred type
// of validator (the one that receives dispatcher as an argument)
const validator = useDebounceCallback<IValidatorDeferred<ITextValidityState>>(
(d) => {
const isValid = !text.length || text.length % 2 === 1;

d({
isValid,
error: !isValid ? new Error('text length should be an odd length') : undefined,
});
},
150,
[text]
);

// validity state type if inferred from validator
const [validity] = useValidator(validator, [validator]);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't know how I feel about this one. It almost feels like the better UX here would to be to either make this into useValidatorState, or to at least pass the value you are validating to useValidator.

Also, how it's set up here makes it so useValidator seems to be be pretty useless if you weren't using useDebounceCallback. You could otherwise just validate on input or on render, which both seem like better practices. Maybe I'm missing something though.

Copy link
Contributor Author

@xobotyi xobotyi Jun 2, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

to either make this into useValidatorState

It will be implemented as a separate hook later.

at least pass the value you are validating to useValidator

This will strict you to use validated value only, but what if you want to validate multiple values simultaneously? How to pass them to the validator? Dependencies list is an array, attempt to determine values depending on positions can cause inambiguos bugs.

seems to be be pretty useless if you weren't using useDebounceCallback.

Althoug it supports synchronous validation - it was designed mostly for async\deferred validation.

You could otherwise just validate on input or on render, which both seem like better practices.

On-input validation makes multivalue validation very complicated complicated.
On-render validation forces you to create validity storage by hand and does validation on ach render instead of on-change.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it was designed mostly for async\deferred validation.

How about we rename this hook to useAsyncValidator then? Or useValidatorEffect? I think that'd convey the intended use case better.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It is state, not the effect, also it is not the async - only, as for my code I have several synchronous validators.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Gotcha. I'm okay rolling with this for now, but I'm still not sold on it.


return (
<div>
<div>
In case below input has an odd number of characters - it is valid, otherwise, the error
message is shown
</div>
<br />

{validity.isValid === false && <div style={{ color: 'red' }}>{validity.error?.message}</div>}
<input
type="text"
value={text}
onChange={(ev) => {
setText(ev.target.value);
}}
/>
</div>
);
};
Loading