Skip to content

Commit

Permalink
feat(i18n): implement i18n in pages and accommodate/use server side 4…
Browse files Browse the repository at this point in the history
…04 redirects

- Make sure a string is sent to API instead of undefined
- Make error page look proper
  • Loading branch information
MathiasKandelborg committed Oct 22, 2020
1 parent 15baffd commit 17bdfca
Show file tree
Hide file tree
Showing 10 changed files with 84 additions and 27 deletions.
2 changes: 1 addition & 1 deletion components/UI/Pages/Category/SingleCategoryPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ const SingleCategoryPage: React.FC<ICategoryPageProps> = (props) => {
component={MUI.Paper}
className={classes.paper}>
<ListProduct
categorySlug={category?.url.current}
categorySlug={category?.url?.current}
products={products}
/>
</MUI.Grid>
Expand Down
35 changes: 26 additions & 9 deletions pages/[page].tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,29 +9,39 @@ import routes from '@util/api/queries/allRoutes'
import { CONSTANTS, ui } from '@util/settings'
import { APIRoute } from 'cms/APIRoute'
import groq from 'groq'
import { GetStaticPaths, GetStaticProps, InferGetStaticPropsType } from 'next'
import {
GetStaticProps,
GetStaticPropsContext,
InferGetStaticPropsType
} from 'next'
import { NextSeo } from 'next-seo'
import { useRouter } from 'next/router'
import { PageProps } from 'PageProps'
import { useEffect, useState } from 'react'

interface ICustomPageProps extends PageProps {
interface ICustomPageProps extends PageProps, GetStaticPropsContext {
currentRoute: APIRoute | null
preview?: boolean
previewData?: Record<string, string>
}

export const getStaticPaths: GetStaticPaths = async () => {
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
export const getStaticPaths = async (hmm: unknown) => {
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
console.info(`GetStaticPathsObj: ${hmm}`)
const sanityRoutes: Array<{ slug: { current: string } }> = await getClient(
false
).fetch(routes)

const routeParams: { params: { page: string } }[] = []

sanityRoutes.forEach((route) =>
routeParams.push({ params: { page: `/${route.slug.current}` } })
routeParams.push({
params: { page: `/${route.slug.current}` }
})
)

// eslint-disable-next-line no-console
console.dir(routeParams)

return {
paths: !routeParams[0] ? [{ params: { page: 'REDIRECT' } }] : routeParams,
fallback: true
Expand All @@ -40,7 +50,8 @@ export const getStaticPaths: GetStaticPaths = async () => {

export const getStaticProps: GetStaticProps<ICustomPageProps> = async (ctx) => {
const { preview, params } = ctx

// eslint-disable-next-line no-console
console.log(ctx)
const config = await getSanityConfig()

const page = params && typeof params.page === 'string' ? params.page : ''
Expand All @@ -49,14 +60,20 @@ export const getStaticProps: GetStaticProps<ICustomPageProps> = async (ctx) => {
pageSlug: page
})

if (!fetchedRoute || !fetchedRoute._id) {
return {
unstable_notFound: true
}
}

return {
props: {
...config,
preview: Boolean(preview),
currentRoute: fetchedRoute || null,
currentRoute: fetchedRoute,
...ctx
},
revalidate: 1
revalidate: 10
}
}

Expand Down
37 changes: 27 additions & 10 deletions pages/_error.tsx
Original file line number Diff line number Diff line change
@@ -1,22 +1,39 @@
import { PageAnimation } from '@components/UI'
import * as MUI from '@material-ui/core'
import getSanityConfig from '@util/api/calls/getSanityConfig'
import { AnimatePresence } from 'framer-motion'
import { NextPage } from 'next'
import { PageProps } from 'PageProps'

interface IErrorProps {
statusCode: string | undefined
interface IErrorProps extends PageProps {
statusCode: number | undefined
}

const Error: React.FC<IErrorProps> = (props) => {
const Error: NextPage<IErrorProps> = (props) => {
const { statusCode } = props

return (
<PageAnimation>
<MUI.Typography>
{statusCode
? `An error occurred on the server: ${statusCode}`
: `An error occurred on the client`}
</MUI.Typography>
</PageAnimation>
<AnimatePresence>
<PageAnimation>
<MUI.Typography>
{statusCode
? `An error occurred on the server: ${statusCode}`
: `An error occurred on the client`}
</MUI.Typography>
</PageAnimation>
</AnimatePresence>
)
}

Error.getInitialProps = async (ctx) => {
const config = await getSanityConfig()
// console.log(ctx)

return {
...config,
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
statusCode: ctx.res?.statusCode
}
}

export default Error
6 changes: 5 additions & 1 deletion pages/category/[category].tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,9 @@ export const getStaticPaths: GetStaticPaths = async () => {
const categoriesArr: { params: { category: string } }[] = []

categories.forEach((category) => {
categoriesArr.push({ params: { category: category.url.current } })
categoriesArr.push({
params: { category: category?.url?.current || 'UNDEFINED' }
})
})

return {
Expand All @@ -48,6 +50,8 @@ export const getStaticProps: GetStaticProps<Omit<

const products = await getProductsByCategory(category._id)

if (!category) return { unstable_notFound: true }

return {
props: {
...config,
Expand Down
2 changes: 2 additions & 0 deletions pages/category/[category]/[product].tsx
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,8 @@ export const getStaticProps: GetStaticProps<Omit<

const product = await getSingleProductBySlug(slug)

if (!product) return { unstable_notFound: true }

return {
props: {
...config,
Expand Down
17 changes: 16 additions & 1 deletion pages/index.tsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,29 @@
import PageSEO from '@components/HoC/SEO/Page'
import HomePage from '@components/UI/Pages/Home/HomePage'
import getSanityConfig from '@util/api/calls/getSanityConfig'
import resolveTranslationFiles from '@util/i18n/resolveTranslationFiles'
import { GetStaticProps, InferGetStaticPropsType } from 'next'
import { PageProps } from 'PageProps'

export const getStaticProps: GetStaticProps<PageProps> = async (ctx) => {
const config = await getSanityConfig()

const error = 'I18n is not enabled in `next.config.js`'

/**
* Get translation files based on current locale
*
* `translation` is handled like an export default js module
* To access keys in the file, use object notation
*/
const translation = resolveTranslationFiles({
locale: ctx.locale || error,
locales: ctx.locales || [error],
namespaces: ['homePage', 'test']
})

return {
props: { ...ctx, ...config },
props: { ...ctx, ...config, translation },
revalidate: 3600
}
}
Expand Down
2 changes: 1 addition & 1 deletion util/api/calls/getAllProductsByCategory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import productsByCategory from '../queries/allProductsByCategory'
*/
async function getProductsByCategory(id: string): Promise<Product[]> {
const data: Product[] = await getClient(false).fetch(productsByCategory, {
id
id: `${id}`
})

return data
Expand Down
4 changes: 3 additions & 1 deletion util/api/calls/getSingleCategoryBySlug.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@ import categoryBySlug from '../queries/singleCategoryBySlug'
* @returns {Promise<Category>} The category provided by slug
*/
async function getCategoryBySlug(slug: string): Promise<Category> {
const data: Category = await getClient(false).fetch(categoryBySlug, { slug })
const data: Category = await getClient(false).fetch(categoryBySlug, {
slug: `${slug}`
})

return data
}
Expand Down
2 changes: 1 addition & 1 deletion util/api/calls/getSingleProductFromSlug.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import singleProductFromSlug from '../queries/singleProductBySlug'
*/
async function getSingleProductBySlug(slug: string): Promise<Product> {
const data: Product = await getClient(false).fetch(singleProductFromSlug, {
slug
slug: `${slug}`
})

return data
Expand Down
4 changes: 2 additions & 2 deletions util/generateProductParamsArr.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,8 @@ async function generateProductParamsArr(): Promise<IParams> {
if (productInCategory)
paramsArr.push({
params: {
category: cat.url.current,
product: prod.url.current
category: cat.url?.current,
product: prod.url?.current
}
})
})
Expand Down

0 comments on commit 17bdfca

Please sign in to comment.