movie-web/src/hooks/useRandomTranslation.ts

23 lines
516 B
TypeScript
Raw Normal View History

2023-10-25 18:16:25 +02:00
import { useCallback, useMemo } from "react";
2023-10-25 16:58:38 +02:00
import { useTranslation } from "react-i18next";
export function useRandomTranslation() {
const { t } = useTranslation();
2023-10-25 18:16:25 +02:00
const seed = useMemo(() => Math.random(), []);
2023-10-25 16:58:38 +02:00
2023-10-25 18:16:25 +02:00
const getRandomTranslation = useCallback(
(key: string) => {
const res = t(key, { returnObjects: true });
2023-10-25 16:58:38 +02:00
2023-10-25 18:16:25 +02:00
if (Array.isArray(res)) {
return res[Math.floor(seed * res.length)];
}
2023-10-25 16:58:38 +02:00
2023-10-25 18:16:25 +02:00
return res;
},
[t, seed]
);
2023-10-25 16:58:38 +02:00
return { t: getRandomTranslation };
}