Created
April 12, 2019 07:07
-
-
Save Swiip/457f50cb4c4da0698f39cc06db2cad9e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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