R
R
Rustam2020-06-20 23:33:09
typescript
Rustam, 2020-06-20 23:33:09

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;
  }, {});
};

When called, the useQueryParams hook is passed an array of strings, these are the parameters keys that are needed for the component.
useQueryParams returns a key-value object and a function that will change the parameters.

Problems:
1. How can I remove all side effects in useEffect?
2. How to use a hook in more than one component? those. so that two components using useQueryParams do not overwrite each other's parameters.
3. What is the correct way to set parameters in the URL?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Robur, 2020-06-21
@Robur

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 question

Ask a Question

731 491 924 answers to any question