hensei-web/pages/new/index.tsx
Justin Edmund a98585a334 Implement setUserToken util function
This function sets axios's default headers to be included before all queries.

We need to call `setUserToken` in _app.tsx so that the defaults are set before every client-side call, and we also need to call it in every instance of `setServerSideProps`.

As a result, wherever we use `getCookies` and construct a `headers` object, we can remove it. Right now, we've only removed it on the top-level pages.
2022-12-22 21:41:38 -08:00

109 lines
2.4 KiB
TypeScript

import React, { useEffect } from 'react'
import { serverSideTranslations } from 'next-i18next/serverSideTranslations'
import Party from '~components/Party'
import { appState } from '~utils/appState'
import setUserToken from '~utils/setUserToken'
import api from '~utils/api'
import type { NextApiRequest, NextApiResponse } from 'next'
interface Props {
jobs: Job[]
jobSkills: JobSkill[]
raids: Raid[]
sortedRaids: Raid[][]
}
const NewRoute: React.FC<Props> = (props: Props) => {
function callback(path: string) {
// This is scuffed, how do we do this natively?
window.history.replaceState(null, `Grid Tool`, `${path}`)
}
useEffect(() => {
persistStaticData()
}, [persistStaticData])
function persistStaticData() {
appState.raids = props.raids
appState.jobs = props.jobs
appState.jobSkills = props.jobSkills
}
return <Party new={true} raids={props.sortedRaids} pushHistory={callback} />
}
export const getServerSidePaths = async () => {
return {
paths: [
// Object variant:
{ params: { party: 'string' } },
],
fallback: true,
}
}
// prettier-ignore
export const getServerSideProps = async ({ req, res, locale, query }: { req: NextApiRequest, res: NextApiResponse, locale: string, query: { [index: string]: string } }) => {
// Set headers for server-side requests
setUserToken(req, res)
let { raids, sortedRaids } = await api.endpoints.raids
.getAll()
.then((response) => organizeRaids(response.data))
let jobs = await api.endpoints.jobs
.getAll()
.then((response) => {
return response.data
})
let jobSkills = await api.allSkills().then((response) => {
return response.data
})
return {
props: {
jobs: jobs,
jobSkills: jobSkills,
raids: raids,
sortedRaids: sortedRaids,
...(await serverSideTranslations(locale, ["common"])),
// Will be passed to the page component as props
},
}
}
const organizeRaids = (raids: Raid[]) => {
// Set up empty raid for "All raids"
const all = {
id: '0',
name: {
en: 'All raids',
ja: '全て',
},
slug: 'all',
level: 0,
group: 0,
element: 0,
}
const numGroups = Math.max.apply(
Math,
raids.map((raid) => raid.group)
)
let groupedRaids = []
for (let i = 0; i <= numGroups; i++) {
groupedRaids[i] = raids.filter((raid) => raid.group == i)
}
return {
raids: raids,
sortedRaids: groupedRaids,
}
}
export default NewRoute