Skip to content

Instantly share code, notes, and snippets.

@Swiip
Created April 12, 2019 07:07
Show Gist options
  • Save Swiip/457f50cb4c4da0698f39cc06db2cad9e to your computer and use it in GitHub Desktop.
Save Swiip/457f50cb4c4da0698f39cc06db2cad9e to your computer and use it in GitHub Desktop.
import React from "react";
import { string } from "prop-types";
import set from "lodash.set";
import { useSSR } from "react-i18next";
import i18n from "i18next";
import { useQuery } from "react-apollo-hooks";
import { gql } from "apollo-boost";
import i18next from "./i18next";
import { NamespaceProvider } from "./namespace";
const i18nQuery = gql`
query I18n {
i18n {
key
value
}
}
`;
const dataToStore = data => {
const store = {};
data.i18n.forEach(({ key, value }) => {
set(store, key, value);
});
return store;
};
const withI18next = ({ debug = false }) => Component => {
const Extended = ({ initialLanguage, ...props }) => {
const query = useQuery(i18nQuery);
const store = dataToStore(query.data);
if (!process.browser) {
i18next.initializedLanguageOnce = false;
}
useSSR(store, initialLanguage, { i18n: i18next });
if (debug) {
console.log("[withI18next]", store, i18next);
}
return (
<NamespaceProvider value={i18n.options.defaultNS}>
<Component {...props} />
</NamespaceProvider>
);
};
Extended.getInitialProps = async props => {
const composedInitialProps = Component.getInitialProps
? await Component.getInitialProps(props)
: {};
return {
...composedInitialProps,
initialLanguage: props.ctx.req ? props.ctx.req.i18n.language : null
};
};
Extended.propTypes = {
initialLanguage: string
};
return Extended;
};
export default withI18next;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment