core-plugin-api: make useTranslationRef handle translation ref update
Signed-off-by: Patrik Oldsberg <poldsberg@gmail.com>
This commit is contained in:
@@ -21,7 +21,7 @@ import {
|
||||
withLogCollector,
|
||||
} from '@backstage/test-utils';
|
||||
import { renderHook } from '@testing-library/react-hooks';
|
||||
import { createTranslationRef } from './TranslationRef';
|
||||
import { createTranslationRef, TranslationRef } from './TranslationRef';
|
||||
import { useTranslationRef } from './useTranslationRef';
|
||||
// eslint-disable-next-line @backstage/no-relative-monorepo-imports
|
||||
import { I18nextTranslationApi } from '../../../core-app-api/src/apis/implementations/TranslationApi';
|
||||
@@ -284,4 +284,42 @@ describe('useTranslationRef', () => {
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it('should handle translationRef switches', async () => {
|
||||
const ref1 = createTranslationRef({
|
||||
id: 'test1',
|
||||
messages: {
|
||||
key: 'default1',
|
||||
},
|
||||
});
|
||||
const ref2 = createTranslationRef({
|
||||
id: 'test2',
|
||||
messages: {
|
||||
key: 'default2',
|
||||
},
|
||||
});
|
||||
|
||||
const languageApi = AppLanguageSelector.create();
|
||||
const translationApi = I18nextTranslationApi.create({ languageApi });
|
||||
|
||||
const { result, rerender } = renderHook(
|
||||
({ translationRef }) => useTranslationRef(translationRef),
|
||||
{
|
||||
wrapper: ({ children }) => (
|
||||
<TestApiProvider
|
||||
apis={[
|
||||
[translationApiRef, translationApi],
|
||||
[errorApiRef, { post: jest.fn() }],
|
||||
]}
|
||||
children={children}
|
||||
/>
|
||||
),
|
||||
initialProps: { translationRef: ref1 as TranslationRef },
|
||||
},
|
||||
);
|
||||
|
||||
expect(result.current.t('key')).toBe('default1');
|
||||
rerender({ translationRef: ref2 });
|
||||
expect(result.current.t('key')).toBe('default2');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -14,7 +14,7 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { errorApiRef, useApi } from '../apis';
|
||||
import {
|
||||
translationApiRef,
|
||||
@@ -73,6 +73,16 @@ export const useTranslationRef = <
|
||||
};
|
||||
}, [observable, onError]);
|
||||
|
||||
// Keep track of if the provided translation ref changes, and in that case update the snapshot
|
||||
const initialRenderRef = useRef(true);
|
||||
useEffect(() => {
|
||||
if (initialRenderRef.current) {
|
||||
initialRenderRef.current = false;
|
||||
} else {
|
||||
setSnapshot(translationApi.getTranslation(translationRef));
|
||||
}
|
||||
}, [translationApi, translationRef]);
|
||||
|
||||
if (!snapshot.ready) {
|
||||
throw new Promise<void>(resolve => {
|
||||
const subscription = observable.subscribe({
|
||||
|
||||
Reference in New Issue
Block a user