import * as queryString from 'query-string';
import { useImmer } from 'use-immer';
import { useEventListener } from '../useEventListener';

export function useQueryString(path?: string): any {
   const [query, setQuery] = useImmer(queryString.parseUrl(window.location.href).query);

   const eventListener = (event: any): void => {
      if (window.location.pathname === path || !path) {
         setQuery(() => queryString.parseUrl(window.location.href).query);
      }
   };

   useEventListener('popstate', eventListener);

   return query;
}
