next-rosetta icon indicating copy to clipboard operation
next-rosetta copied to clipboard

locale switching does not trigger rerender

Open asyncink opened this issue 2 years ago • 2 comments

hello and thank you for your package!

we use it since first releases and happy now with removing state from provider and new ref implementation. bug with stale dict affected us too.

for now we noticed one more bug and it looks like it is connected with refs implementation.

the t function from useI18n hook is not changing when locale is switched.

so if we have something like:

const navigationItems = useMemo(
  () =>
    navigation.map(({ name, url }) => (
      <Link
        href={url}
        key={name}
      >
        {t(name)}
      </Link>
    )),
  [navigation, asPath, t]
)

return <nav>{navigationItems}</nav>

and then if we switch locale - the hook is not rerunning and page is not rerendered. workaround here is explicitly add locale from router to useMemo deps array:

const {locale} = useRouter()

const navigationItems = useMemo(
  () =>
    navigation.map(({ name, url }) => (
      <Link
        href={url}
        key={name}
      >
        {t(name)}
      </Link>
    )),
  [navigation, asPath, t, locale]
)

return <nav>{navigationItems}</nav>

but this workaround causes eslint-react-hooks error since locale is not used inside hook but still present in its deps array. it looks like t function should change in locale change.

in examples below assuming that navigation is something like:

const navigation = [
  {
    name: 'navigation.foo',
    url: '/foo'
  },
  {
    name: 'navigation.bar',
    url: '/bar'
  },
]

and our locale is:

const locale = {
  navigation: {
    foo: 'Foo Page',
    bar: 'Bar Page'
  }
}

asyncink avatar Jan 25 '22 12:01 asyncink

Hi @asyncink

Looks like a valid reason to revert https://github.com/useflyyer/next-rosetta/pull/25

In the meantime you can go back to version ^1.0.0 where t changes when locale changes.

lopezjurip avatar Jan 28 '22 15:01 lopezjurip

Hi @lopezjurip

Thank you for your reply!

I think that implementation with refs is quite good since it fixes bug with stale dict during next page transitions. For the same reason we can't switch to 1.x.x version.

Unfortunately I have no time right now to figure out how to fix t func in next-rosetta codebase, but I will try later!

It looks like we should add locale to deps somewhere inside provider/hook and then return new t every time locale changes.

asyncink avatar Jan 28 '22 20:01 asyncink