Skip to content

Commit

Permalink
implement useDecodeValue hook
Browse files Browse the repository at this point in the history
  • Loading branch information
am1rb committed Jan 7, 2024
1 parent 1853f8f commit fdac064
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 0 deletions.
29 changes: 29 additions & 0 deletions src/useDecodeValue.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { renderHook } from '@testing-library/react';
import { useDecodeValue } from '../src/useDecodeValue';
import { SAMPLE_KEY, getTestData } from './utils/getTestData';

describe('useDecodeValue', () => {
it('should memoize the decoded value', () => {
const testData = getTestData();

const { result, rerender } = renderHook(
({ rawValue }: { rawValue: string | null }) =>
useDecodeValue(SAMPLE_KEY, rawValue, testData.options),
{ initialProps: { rawValue: testData.storedValue.ok } }
);

const initialDecodedValue = result.current;

rerender({ rawValue: testData.storedValue.ok });
rerender({ rawValue: testData.storedValue.ok });
rerender({ rawValue: testData.storedValue.ok });

expect(result.current).toBe(initialDecodedValue);

rerender({
rawValue: testData.options.encoder({ id: 2, label: 'new value' }),
});

expect(result.current).not.toBe(initialDecodedValue);
});
});
14 changes: 14 additions & 0 deletions src/useDecodeValue.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import * as React from 'react';
import { z } from 'zod';
import { Options } from './types/Options';
import { decodeRawValue } from './utils/decodeRawValue';

export function useDecodeValue<Schema extends z.ZodTypeAny>(
key: string,
rawValue: string | null,
options: Options<Schema>
): z.infer<Schema> | undefined {
return React.useMemo(() => decodeRawValue(key, rawValue, options), [
rawValue,
]);
}

0 comments on commit fdac064

Please # to comment.