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

Move useQueryPersistedFilterState to ui-core #23743

Merged
merged 4 commits into from
Aug 20, 2024
Merged
Show file tree
Hide file tree
Changes from all 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
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
import {act, renderHook} from '@testing-library/react-hooks';
import React from 'react';
import {MemoryRouter} from 'react-router';

import {useQueryPersistedFilterState} from '../useQueryPersistedFilterState';

const wrapper = ({
initialEntries,
}: {
initialEntries?: React.ComponentProps<typeof MemoryRouter>['initialEntries'];
} = {}) => {
return ({children}: {children: React.ReactNode}) => (
<MemoryRouter initialEntries={initialEntries}>{children}</MemoryRouter>
);
};

describe('useQueryPersistedFilterState', () => {
afterEach(() => {
jest.clearAllMocks();
});

it('should initialize with decoded state from query string', () => {
const {result} = renderHook(
() => useQueryPersistedFilterState<{filterA: string[]; filterB: string[]}>(['filterA', 'filterB']),
{
wrapper: wrapper({
initialEntries: [
`/?filterA=${encodeURIComponent(
JSON.stringify(['value1']),
)}&filterB=${encodeURIComponent(JSON.stringify(['value2']))}`,
],
}),
},
);

expect(result.current.state).toEqual({
filterA: ['value1'],
filterB: ['value2'],
});
});

it('should encode the state correctly when setting a value', () => {
const {result} = renderHook(
() => useQueryPersistedFilterState<{filterA: string[]; filterB: string[]}>(['filterA', 'filterB']),
{wrapper: wrapper()},
);

act(() => {
result.current.setters.setFilterA(['newValue']);
});

expect(result.current.state.filterA).toEqual(['newValue']);
});

it('should create setters dynamically for each filter field', () => {
const {result} = renderHook(
() => useQueryPersistedFilterState<{filterA: string[]; filterB: string[]}>(['filterA', 'filterB']),
{wrapper: wrapper()},
);

expect(result.current.setters).toHaveProperty('setFilterA');
expect(result.current.setters).toHaveProperty('setFilterB');

act(() => {
result.current.setters.setFilterA(['valueA']);
result.current.setters.setFilterB(['valueB']);
});

expect(result.current.state.filterA).toEqual(['valueA']);
expect(result.current.state.filterB).toEqual(['valueB']);
});

it('should handle undefined or empty values correctly', () => {
const {result} = renderHook(
() =>
useQueryPersistedFilterState<{filterA: string[] | undefined; filterB: string[] | undefined}>([
'filterA',
'filterB',
]),
{wrapper: wrapper()},
);

act(() => {
result.current.setters.setFilterA([]);
result.current.setters.setFilterB(undefined);
});

expect(result.current.state.filterA).toEqual([]);
expect(result.current.state.filterB).toEqual([]);
});

it('should return memoized setters', () => {
const FIELDS = ['filterA', 'filterB'] as const;
const {result, rerender} = renderHook(
() => useQueryPersistedFilterState<{filterA: string[]; filterB: string[]}>(FIELDS),
{wrapper: wrapper()},
);

const initialSetters = result.current.setters;

rerender();

expect(result.current.setters).toBe(initialSetters);
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import {SetStateAction, useMemo} from 'react';

import {useQueryPersistedState} from './useQueryPersistedState';

type SetterType<T extends Record<string, any>, K extends keyof T & string> = {
[P in K as `set${Capitalize<P>}`]: (value: SetStateAction<T[P]>) => void;
};

export const useQueryPersistedFilterState = <T extends Record<string, any | undefined>>(
filterFields: readonly (keyof T)[],
): {
state: T;
setState: React.Dispatch<React.SetStateAction<T>>;
setters: SetterType<T, Extract<keyof T, string>>;
} => {
const encode = (filters: T) => {
return filterFields.reduce((acc, field) => {
const value = filters[field];
acc[field] = value?.length
? (JSON.stringify(value) as T[keyof T])
: (undefined as T[keyof T]);
return acc;
}, {} as T);
};

const decode = (qs: Record<string, string | undefined>) => {
return filterFields.reduce((acc, field) => {
acc[field] = qs[field as string] ? JSON.parse(qs[field]!) : [];
return acc;
}, {} as T);
};

const [state, setState] = useQueryPersistedState<T>({
encode,
decode,
});

const createSetters = () => {
const setters = {} as SetterType<T, Extract<keyof T, string>>;

filterFields.forEach((field) => {
const fieldAsString = field as keyof T & string;
const key = `set${
fieldAsString.charAt(0).toUpperCase() + fieldAsString.slice(1)
}` as keyof SetterType<T, Extract<keyof T, string>>;

setters[key] = ((value: any) => {
setState((prevState: T) => ({
...prevState,
[fieldAsString]: value instanceof Function ? value(prevState[fieldAsString]) : value,
}));
}) as any;
});

return setters;
};

const setters = useMemo(createSetters, [filterFields, setState]);

return {
state,
setState,
setters,
};
};