Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import { zodResolver } from '@hookform/resolvers/zod';
- import { format } from 'date-fns';
- import { useSearchParams } from 'next/navigation';
- import { useState } from 'react';
- import { useForm } from 'react-hook-form';
- import { usePathname, useRouter } from '@/utils/intl-navigation';
- import { TableFilterSchemaType, tableFilterSchema } from './TableFilter.types'
- export const actions = (tableId) => {
- const [selectedType, setSelectedType] = useState('all');
- const [selectedStatus, setSelectedStatus] = useState('all');
- const [selectedBlock, setSelectedBlock] = useState('all');
- const router = useRouter();
- const pathname = usePathname();
- const searchParams = useSearchParams();
- const { register, handleSubmit, control } = useForm<TableFilterSchemaType>({
- resolver: zodResolver(tableFilterSchema),
- values: {
- cpf: searchParams.get('cpf') ?? '',
- date: {
- startDate: searchParams.get('startDate') ? new Date(searchParams.get('startDate')!) : null,
- endDate: searchParams.get('endDate') ? new Date(searchParams.get('endDate')!) : null,
- },
- email: searchParams.get('email') ?? '',
- status: searchParams.get('status') ?? '',
- type: searchParams.get('type') ?? '',
- cognitoId: searchParams.get('cognitoId') ?? '',
- block: searchParams.get('block') ?? '',
- },
- });
- const handleSelectFactory = (value, key, callback) => {
- callback(value);
- register(key).onChange({ target: { value } });
- }
- const handleFilterSubmit = ({
- cpf,
- date,
- email,
- status,
- type,
- cognitoId,
- block,
- }: TableFilterSchemaType) => {
- const params = new URL(document.location.toString()).searchParams;
- const setParam = (key, value) => {
- value ? params.set(key, value) : params.delete(key);
- }
- setParam('cpf', cpf);
- setParam('startDate', date.startDate ? format(date.startDate, 'yyyy-MM-dd HH:mm:ss') : null);
- setParam('endDate', date.endDate ? format(date.endDate, 'yyyy-MM-dd HH:mm:ss') : null);
- setParam('email', email);
- setParam('status', status);
- setParam('type', type);
- setParam('cognitoId', cognitoId);
- setParam('block', block);
- params.set(`${tableId}Page`, '0');
- params.set(`${tableId}PageSize`, params.get(`${tableId}PageSize`) || '10');
- router.push(`${pathname}?${params.toString()}`);
- };
- const handleSelectType = (value: string) => handleSelectFactory(value, 'type', setSelectedType)
- const handleSelectStatus = (value: string) => handleSelectFactory(value, 'status', setSelectedStatus)
- const handleSelectBlock = (value: string) => handleSelectFactory(value, 'block', setSelectedBlock)
- return {
- handleFilterSubmit,
- handleSelectType,
- handleSelectStatus,
- handleSelectBlock,
- selectedType,
- selectedStatus,
- selectedBlock,
- handleSubmit,
- control,
- register,
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement