How to read files on the client-side not only on server side?

324 Views Asked by At

We are making an npm react package (by tsdx library), a custom hook for multi-languaging react projects. Developers who install this package need to make a config.json file at the root and a Languages.json file in the public folder of their Next.js project. What we need is that we can read Languages.json on the client-side of the app.

Package files: LanguageProvider.tsx: A react context that stores the current locale state.

UseTranslation.tsx: A custom hook that gets the locale from the context and finds the key from the same locale in Languages.json.

export function useTranslation() {
  const { locale } = useContext(LanguageContext);
  let LanguagesFile;
  if (typeof window === 'undefined') {
    const fs = require('fs');
    LanguagesFile = fs.readFileSync("./public/Languages.json", 'utf8');
  }
  
  function t(key: string) {
    if (typeof LanguagesFile !== 'undefined') {
      const Languages = JSON.parse(LanguagesFile);
      if (!Languages && !Languages[locale] && !Languages[locale][key]) {
        console.warn(`No string '${key}' for locale '${locale}'`);
        return false;
      } else {
        return Languages[locale][key].toString() || '';
      }
    }
  }
  return t;
}

When I log Languages.json file from UseTranslation.tsx, it shows me the data on the server, but it is undefined on the client-side of the app.

0

There are 0 best solutions below