Answer the question
In order to leave comments, you need to log in
How to make a Hook to work with query parameters?
I want to set query parameters from the component in the URL line, since the logic turns out to be large, I want to put it in a separate hook.
I did this:
import { isBrowser } from '../lib/is-browser';
export const useQueryParams = (desiredParams: string[]) => {
const params = isBrowser() ? window.location.search : null;
const queryParams = params ? parseQueryParams(params, desiredParams) : null;
const changeQueryParams = (queryParams: Record<string, string>): void => {
const params = new URLSearchParams(Object.entries(queryParams).filter(([, value]) => !!value));
updateURL(params.toString());
};
return [queryParams, changeQueryParams] as const;
};
const updateURL = (param: string): void => {
if (history.pushState) {
const baseUrl =
window.location.protocol + '//' + window.location.host + window.location.pathname;
const newUrl = baseUrl + (param ? `?${param}` : '');
history.pushState(null, '', newUrl);
} else {
console.warn('History API не поддерживается');
}
};
export const parseQueryParams = (params: string, desiredParams: string[],): Record<string, string> => {
const searchParams = new URLSearchParams(params);
return desiredParams.reduce((acc: Record<string, string>, key) => {
if (searchParams.has(key)) acc[key] = searchParams.get(key) as string;
return acc;
}, {});
};
Answer the question
In order to leave comments, you need to log in
1. the question is not clear, what are the effects, with useEffect here? there is not enough code how do you use it all and what are the problems.
2. updateUrl should save all the parameters that were already in the url and add/update new ones. Everything is deleted from you and only transferred ones are put.
3. The gold standard is to use routing. If you do not want or do not fit - then any bike, yours will do too.
4. Are you sure you want the url? maybe localStorage is better for you?
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question