Developer
Developer

Reputation: 81

How to refresh page after change language in nextjs? Clientside to serverside

I am developing nextjs app. I get localized data by using query params ('website.com/data?lang=en'). So, when user change app locale, how can I refresh or trigger getServerSideProps (getStaticProps)? Or How to correctly detect locale change?

 // Client side change language
const changeLanguage = (locale) => {
  router.push(router.asPath, router.asPath, { locale });
};

const fetchData = async (locale) =>
  await client()
    .get('/api/products', { params: { lang: locale } })
    .then((res) => ({
      index: res.data
    }))
    .catch(() => ());

export const getServerSideProps = async (context) => {
  const { locale } = context;
  const data = await fetchData(locale);

  return {
    props: data,
    notFound
  };
};
export default Index;

Note: router.push not trigger serversideprops

Upvotes: 2

Views: 489

Answers (2)

Ebrahim Abdollahian
Ebrahim Abdollahian

Reputation: 618

If you want the locale change to result in an SSR fetch, ensure that the navigation using router.push() or router.replace(). This triggers a full page refresh which includes server-side data fetching.

function changeLocale(newLocale) {
const router = useRouter();
const { pathname, query, asPath } = router;
router.push({ pathname, query }, asPath, { locale: newLocale });
}

Upvotes: 0

spirift
spirift

Reputation: 3072

If all you want to do is reload the page you can you the browser window.location.reload() function.

Upvotes: -1

Related Questions