import * as React from 'react';
import { useLocation } from 'react-router-dom';
import { useLocalStorage } from 'usehooks-ts';
import { TOKEN_KEY } from '../consts';

export function useToken() {
  const { search } = useLocation();
  const query = new URLSearchParams(search);
  const paramToken = query.get(TOKEN_KEY);

  const [localToken, setLocalToken] = useLocalStorage(TOKEN_KEY, '');

  React.useEffect(() => {
    if (paramToken) {
      setLocalToken(paramToken);
    }
  }, [paramToken]);

  return localToken;
}
