Skip to content

Commit

Permalink
fix: prevent clicks while routing is occurring
Browse files Browse the repository at this point in the history
  • Loading branch information
alexgoff committed Aug 29, 2024
1 parent 39ac2e6 commit dd68386
Showing 1 changed file with 22 additions and 19 deletions.
41 changes: 22 additions & 19 deletions components/global/Header/LanguageSelect/index.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { useTransition } from "react";
import PropTypes from "prop-types";
import { useEffect, useState } from "react";
import { useRouter, useSearchParams, usePathname } from "next/navigation";
import { useTranslation } from "react-i18next";
import * as Styled from "./styles";
Expand All @@ -18,51 +18,54 @@ const filterSearchParams = (searchParams) => {
};

export default function LanguageSelect({ id }) {
const [isLoading, setLoading] = useState(false);
const router = useRouter();
const pathname = usePathname();
const searchParams = useSearchParams();
const {
t,
i18n: { changeLanguage, resolvedLanguage: locale },
} = useTranslation();
const [isPending, startTransition] = useTransition();

const isDefaultLocale = fallbackLng.includes(locale);

const handleClick = () => {
startTransition(() => {
const newLocale = isDefaultLocale ? "es" : "en";
useEffect(() => {
setLoading(false);
}, [pathname]);

if (newLocale !== locale) {
const parts = pathname?.split("/") || [];
parts.shift();
const handleClick = () => {
const newLocale = isDefaultLocale ? "es" : "en";

if (locale !== fallbackLng) {
parts.shift();
}
if (newLocale !== locale) {
const parts = pathname?.split("/") || [];
parts.shift();

const route = `/${newLocale}/${parts.join("/")}${filterSearchParams(
searchParams
)}`;
changeLanguage(newLocale);
router.replace(route, { scroll: false });
if (locale !== fallbackLng) {
parts.shift();
}
});

const route = `/${newLocale}/${parts.join("/")}${filterSearchParams(
searchParams
)}`;
changeLanguage(newLocale);
setLoading(true);
router.replace(route, { scroll: false });
}
};

return (
<Styled.Fieldset>
<legend className="a-hidden">{t("localize-content")}</legend>
<Styled.Label htmlFor={id} $disabled={isPending}>
<Styled.Label htmlFor={id} $disabled={isLoading}>
<Styled.MobileLabelText role="presentation">
{t("language-select-label")}
</Styled.MobileLabelText>
<span className="a-hidden">{t("espanol-site-name")}</span>
<Styled.Switch
id={id}
checked={!isDefaultLocale}
aria-disabled={isPending}
onClick={handleClick}
aria-disabled={isLoading}
/>
</Styled.Label>
</Styled.Fieldset>
Expand Down

0 comments on commit dd68386

Please sign in to comment.