36 lines
1.0 KiB
TypeScript
36 lines
1.0 KiB
TypeScript
/* eslint-disable canonical/id-match */
|
|
/* eslint-disable @typescript-eslint/naming-convention */
|
|
'use client';
|
|
|
|
import { useRouter, useSearchParams } from 'next/navigation';
|
|
|
|
export function useGetUrlData<T>(): null | T {
|
|
const searchParameters = useSearchParams();
|
|
const data = searchParameters.get('_data_');
|
|
|
|
if (!data) return null;
|
|
|
|
try {
|
|
const decoded = decodeURIComponent(atob(data));
|
|
return JSON.parse(decoded) as T;
|
|
} catch (error) {
|
|
throw new Error('Failed to parse data parameters', { cause: error });
|
|
}
|
|
}
|
|
|
|
export function usePushWithData() {
|
|
const router = useRouter();
|
|
const searchParameters = useSearchParams();
|
|
|
|
return <T>(url: string, parameters: T) => {
|
|
try {
|
|
const base64 = btoa(encodeURIComponent(JSON.stringify(parameters)));
|
|
const parameters_ = new URLSearchParams(searchParameters);
|
|
parameters_.set('_data_', base64);
|
|
router.push(`${url}?${parameters_.toString()}`);
|
|
} catch (error) {
|
|
throw new Error('Failed to serialize data parameters', { cause: error });
|
|
}
|
|
};
|
|
}
|