@@ -2,25 +2,12 @@ import { fetchI18nBundle, getI18nBundle } from '@ui5/webcomponents-base/dist/i18
2
2
import { useEffect , useState } from 'react' ;
3
3
4
4
type TextWithDefault = { key : string ; defaultText : string } ;
5
+ type TextWithPlaceholders = [ TextWithDefault , ...string [ ] ] ;
5
6
6
7
interface I18nBundle {
7
8
getText : ( textObj : TextWithDefault , ...args : any ) => string ;
8
9
}
9
10
10
- export const useI18nBundle = ( bundleName ) : I18nBundle => {
11
- const [ bundle , setBundle ] = useState ( getI18nBundle ( bundleName ) ) ;
12
-
13
- useEffect ( ( ) => {
14
- const fetchAndLoadBundle = async ( ) => {
15
- await fetchI18nBundle ( bundleName ) ;
16
- setBundle ( getI18nBundle ( bundleName ) ) ;
17
- } ;
18
- fetchAndLoadBundle ( ) ;
19
- } , [ ] ) ;
20
-
21
- return bundle ;
22
- } ;
23
-
24
11
const resolveTranslations = ( bundle , texts ) => {
25
12
return texts . map ( ( text ) => {
26
13
if ( Array . isArray ( text ) ) {
@@ -31,14 +18,20 @@ const resolveTranslations = (bundle, texts) => {
31
18
} ) ;
32
19
} ;
33
20
34
- export const useI18nText = ( bundleName : string , ...texts : ( TextWithDefault | any [ ] ) [ ] ) : string [ ] => {
21
+ export const useI18nText = ( bundleName : string , ...texts : ( TextWithDefault | TextWithPlaceholders ) [ ] ) : string [ ] => {
35
22
const i18nBundle : I18nBundle = getI18nBundle ( bundleName ) ;
36
23
const [ translations , setTranslations ] = useState ( resolveTranslations ( i18nBundle , texts ) ) ;
37
24
38
25
useEffect ( ( ) => {
39
26
const fetchAndLoadBundle = async ( ) => {
40
27
await fetchI18nBundle ( bundleName ) ;
41
- setTranslations ( resolveTranslations ( i18nBundle , texts ) ) ;
28
+ setTranslations ( ( prev ) => {
29
+ const next = resolveTranslations ( i18nBundle , texts ) ;
30
+ if ( prev . length === next . length && prev . every ( ( translation , index ) => next [ index ] === translation ) ) {
31
+ return prev ;
32
+ }
33
+ return next ;
34
+ } ) ;
42
35
} ;
43
36
fetchAndLoadBundle ( ) ;
44
37
} , [ fetchI18nBundle ] ) ;
0 commit comments