Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

reset t if ns changes in useTranslation, fix #1517 #1518

Merged
merged 1 commit into from Jun 14, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
17 changes: 16 additions & 1 deletion src/useTranslation.js
Expand Up @@ -2,6 +2,14 @@ import { useState, useEffect, useContext, useRef } from 'react';
import { getI18n, getDefaults, ReportNamespaces, I18nContext } from './context';
import { warnOnce, loadNamespaces, hasLoadedNamespace } from './utils';

const usePrevious = (value, ignore) => {
const ref = useRef();
useEffect(() => {
ref.current = ignore ? ref.current : value;
}, [value, ignore]);
return ref.current;
};

export function useTranslation(ns, props = {}) {
// assert we have the needed i18nInstance
const { i18n: i18nFromProps } = props;
Expand Down Expand Up @@ -48,6 +56,9 @@ export function useTranslation(ns, props = {}) {
}
const [t, setT] = useState(getT);

const joinedNS = namespaces.join();
const previousJoinedNS = usePrevious(joinedNS);

const isMounted = useRef(true);
useEffect(() => {
const { bindI18n, bindI18nStore } = i18nOptions;
Expand All @@ -61,6 +72,10 @@ export function useTranslation(ns, props = {}) {
});
}

if (ready && previousJoinedNS && previousJoinedNS !== joinedNS && isMounted.current) {
setT(getT);
}

function boundReset() {
if (isMounted.current) setT(getT);
}
Expand All @@ -76,7 +91,7 @@ export function useTranslation(ns, props = {}) {
if (bindI18nStore && i18n)
bindI18nStore.split(' ').forEach((e) => i18n.store.off(e, boundReset));
};
}, [i18n, namespaces.join()]); // re-run effect whenever list of namespaces changes
}, [i18n, joinedNS]); // re-run effect whenever list of namespaces changes

// t is correctly initialized by useState hook. We only need to update it after i18n
// instance was replaced (for example in the provider).
Expand Down