Updated saved to use SSR

This commit is contained in:
Justin Edmund 2022-11-16 05:15:12 -08:00
parent 9674a56ccc
commit 513dc8d847

View file

@ -1,37 +1,48 @@
import React, { useCallback, useEffect, useState } from 'react' import React, { useCallback, useEffect, useState } from "react"
import Head from 'next/head' import Head from "next/head"
import { useCookies } from 'react-cookie' import { getCookie } from "cookies-next"
import { queryTypes, useQueryState } from 'next-usequerystate' import { queryTypes, useQueryState } from "next-usequerystate"
import { useRouter } from 'next/router' import { useRouter } from "next/router"
import { useTranslation } from 'next-i18next' import { useTranslation } from "next-i18next"
import InfiniteScroll from 'react-infinite-scroll-component' import InfiniteScroll from "react-infinite-scroll-component"
import { serverSideTranslations } from 'next-i18next/serverSideTranslations' import { serverSideTranslations } from "next-i18next/serverSideTranslations"
import clonedeep from 'lodash.clonedeep' import clonedeep from "lodash.clonedeep"
import api from '~utils/api' import api from "~utils/api"
import { elements, allElement } from '~utils/Element' import useDidMountEffect from "~utils/useDidMountEffect"
import { elements, allElement } from "~utils/Element"
import GridRep from '~components/GridRep' import GridRep from "~components/GridRep"
import GridRepCollection from '~components/GridRepCollection' import GridRepCollection from "~components/GridRepCollection"
import FilterBar from '~components/FilterBar' import FilterBar from "~components/FilterBar"
const SavedRoute: React.FC = () => { import type { NextApiRequest, NextApiResponse } from "next"
interface Props {
teams?: { count: number; total_pages: number; results: Party[] }
raids: Raid[]
sortedRaids: Raid[][]
}
const SavedRoute: React.FC<Props> = (props: Props) => {
// Set up cookies // Set up cookies
const [cookies] = useCookies(['account']) const cookie = getCookie("account")
const headers = (cookies.account) ? { const accountData: AccountCookie = cookie
'Authorization': `Bearer ${cookies.account.access_token}` ? JSON.parse(cookie as string)
} : {} : null
const headers = accountData
? { Authorization: `Bearer ${accountData.token}` }
: {}
// Set up router // Set up router
const router = useRouter() const router = useRouter()
// Import translations // Import translations
const { t } = useTranslation('common') const { t } = useTranslation("common")
// Set up app-specific states // Set up app-specific states
const [loading, setLoading] = useState(true)
const [raidsLoading, setRaidsLoading] = useState(true) const [raidsLoading, setRaidsLoading] = useState(true)
const [scrolled, setScrolled] = useState(false) const [scrolled, setScrolled] = useState(false)
@ -50,36 +61,48 @@ const SavedRoute: React.FC = () => {
const [element, setElement] = useQueryState("element", { const [element, setElement] = useQueryState("element", {
defaultValue: -1, defaultValue: -1,
parse: (query: string) => parseElement(query), parse: (query: string) => parseElement(query),
serialize: value => serializeElement(value) serialize: (value) => serializeElement(value),
}) })
const [raidSlug, setRaidSlug] = useQueryState("raid", { defaultValue: "all" }) const [raidSlug, setRaidSlug] = useQueryState("raid", { defaultValue: "all" })
const [recency, setRecency] = useQueryState("recency", queryTypes.integer.withDefault(-1)) const [recency, setRecency] = useQueryState(
"recency",
queryTypes.integer.withDefault(-1)
)
// Define transformers for element // Define transformers for element
function parseElement(query: string) { function parseElement(query: string) {
let element: TeamElement | undefined = let element: TeamElement | undefined =
(query === 'all') ? query === "all"
allElement : elements.find(element => element.name.en.toLowerCase() === query) ? allElement
return (element) ? element.id : -1 : elements.find((element) => element.name.en.toLowerCase() === query)
return element ? element.id : -1
} }
function serializeElement(value: number | undefined) { function serializeElement(value: number | undefined) {
let name = '' let name = ""
if (value != undefined) { if (value != undefined) {
if (value == -1) if (value == -1) name = allElement.name.en.toLowerCase()
name = allElement.name.en.toLowerCase() else name = elements[value].name.en.toLowerCase()
else
name = elements[value].name.en.toLowerCase()
} }
return name return name
} }
// Set the initial parties from props
useEffect(() => {
if (props.teams) {
setTotalPages(props.teams.total_pages)
setRecordCount(props.teams.count)
replaceResults(props.teams.count, props.teams.results)
}
setCurrentPage(1)
}, [])
// Add scroll event listener for shadow on FilterBar on mount // Add scroll event listener for shadow on FilterBar on mount
useEffect(() => { useEffect(() => {
window.addEventListener("scroll", handleScroll) window.addEventListener("scroll", handleScroll)
return () => window.removeEventListener("scroll", handleScroll); return () => window.removeEventListener("scroll", handleScroll)
}, []) }, [])
// Handle errors // Handle errors
@ -91,31 +114,31 @@ const SavedRoute: React.FC = () => {
} }
}, []) }, [])
const fetchTeams = useCallback(({ replace }: { replace: boolean }) => { const fetchTeams = useCallback(
({ replace }: { replace: boolean }) => {
const filters = { const filters = {
params: { params: {
element: (element != -1) ? element : undefined, element: element != -1 ? element : undefined,
raid: (raid) ? raid.id : undefined, raid: raid ? raid.id : undefined,
recency: (recency != -1) ? recency : undefined, recency: recency != -1 ? recency : undefined,
page: currentPage page: currentPage,
} },
} }
api.savedTeams({...filters, ...{ headers: headers }}) api
.then(response => { .savedTeams({ ...filters, ...{ headers: headers } })
.then((response) => {
setTotalPages(response.data.total_pages) setTotalPages(response.data.total_pages)
setRecordCount(response.data.count) setRecordCount(response.data.count)
if (replace) if (replace)
replaceResults(response.data.count, response.data.results) replaceResults(response.data.count, response.data.results)
else else appendResults(response.data.results)
appendResults(response.data.results)
}) })
.then(() => { .catch((error) => handleError(error))
setLoading(false) },
}) [currentPage, parties, element, raid, recency]
.catch(error => handleError(error)) )
}, [currentPage, parties, element, raid, recency])
function replaceResults(count: number, list: Party[]) { function replaceResults(count: number, list: Party[]) {
if (count > 0) { if (count > 0) {
@ -131,14 +154,13 @@ const SavedRoute: React.FC = () => {
// Fetch all raids on mount, then find the raid in the URL if present // Fetch all raids on mount, then find the raid in the URL if present
useEffect(() => { useEffect(() => {
api.endpoints.raids.getAll() api.endpoints.raids.getAll().then((response) => {
.then(response => {
const cleanRaids: Raid[] = response.data.map((r: any) => r.raid) const cleanRaids: Raid[] = response.data.map((r: any) => r.raid)
setRaids(cleanRaids) setRaids(cleanRaids)
setRaidsLoading(false) setRaidsLoading(false)
const raid = cleanRaids.find(r => r.slug === raidSlug) const raid = cleanRaids.find((r) => r.slug === raidSlug)
setRaid(raid) setRaid(raid)
return raid return raid
@ -147,30 +169,33 @@ const SavedRoute: React.FC = () => {
// When the element, raid or recency filter changes, // When the element, raid or recency filter changes,
// fetch all teams again. // fetch all teams again.
useEffect(() => { useDidMountEffect(() => {
if (!raidsLoading) {
setCurrentPage(1) setCurrentPage(1)
fetchTeams({ replace: true }) fetchTeams({ replace: true })
}
}, [element, raid, recency]) }, [element, raid, recency])
useEffect(() => { // When the page changes, fetch all teams again.
useDidMountEffect(() => {
// Current page changed // Current page changed
if (currentPage > 1) if (currentPage > 1) fetchTeams({ replace: false })
fetchTeams({ replace: false }) else if (currentPage == 1) fetchTeams({ replace: true })
else if (currentPage == 1)
fetchTeams({ replace: true })
}, [currentPage]) }, [currentPage])
// Receive filters from the filter bar // Receive filters from the filter bar
function receiveFilters({ element, raidSlug, recency }: {element?: number, raidSlug?: string, recency?: number}) { function receiveFilters({
if (element == 0) element,
setElement(0) raidSlug,
else if (element) recency,
setElement(element) }: {
element?: number
raidSlug?: string
recency?: number
}) {
if (element == 0) setElement(0)
else if (element) setElement(element)
if (raids && raidSlug) { if (raids && raidSlug) {
const raid = raids.find(raid => raid.slug === raidSlug) const raid = raids.find((raid) => raid.slug === raidSlug)
setRaid(raid) setRaid(raid)
setRaidSlug(raidSlug) setRaidSlug(raidSlug)
} }
@ -180,17 +205,14 @@ const SavedRoute: React.FC = () => {
// Methods: Favorites // Methods: Favorites
function toggleFavorite(teamId: string, favorited: boolean) { function toggleFavorite(teamId: string, favorited: boolean) {
if (favorited) if (favorited) unsaveFavorite(teamId)
unsaveFavorite(teamId) else saveFavorite(teamId)
else
saveFavorite(teamId)
} }
function saveFavorite(teamId: string) { function saveFavorite(teamId: string) {
api.saveTeam({ id: teamId, params: headers }) api.saveTeam({ id: teamId, params: headers }).then((response) => {
.then((response) => {
if (response.status == 201) { if (response.status == 201) {
const index = parties.findIndex(p => p.id === teamId) const index = parties.findIndex((p) => p.id === teamId)
const party = parties[index] const party = parties[index]
party.favorited = true party.favorited = true
@ -204,10 +226,9 @@ const SavedRoute: React.FC = () => {
} }
function unsaveFavorite(teamId: string) { function unsaveFavorite(teamId: string) {
api.unsaveTeam({ id: teamId, params: headers }) api.unsaveTeam({ id: teamId, params: headers }).then((response) => {
.then((response) => {
if (response.status == 200) { if (response.status == 200) {
const index = parties.findIndex(p => p.id === teamId) const index = parties.findIndex((p) => p.id === teamId)
const party = parties[index] const party = parties[index]
party.favorited = false party.favorited = false
@ -222,10 +243,8 @@ const SavedRoute: React.FC = () => {
// Methods: Navigation // Methods: Navigation
function handleScroll() { function handleScroll() {
if (window.pageYOffset > 90) if (window.pageYOffset > 90) setScrolled(true)
setScrolled(true) else setScrolled(false)
else
setScrolled(false)
} }
function goTo(shortcode: string) { function goTo(shortcode: string) {
@ -234,7 +253,8 @@ const SavedRoute: React.FC = () => {
function renderParties() { function renderParties() {
return parties.map((party, i) => { return parties.map((party, i) => {
return <GridRep return (
<GridRep
id={party.id} id={party.id}
shortcode={party.shortcode} shortcode={party.shortcode}
name={party.name} name={party.name}
@ -246,14 +266,16 @@ const SavedRoute: React.FC = () => {
key={`party-${i}`} key={`party-${i}`}
displayUser={true} displayUser={true}
onClick={goTo} onClick={goTo}
onSave={toggleFavorite} /> onSave={toggleFavorite}
/>
)
}) })
} }
return ( return (
<div id="Teams"> <div id="Teams">
<Head> <Head>
<title>{t('saved.title')}</title> <title>{t("saved.title")}</title>
<meta property="og:title" content="Your saved Teams" /> <meta property="og:title" content="Your saved Teams" />
<meta property="og:url" content="https://app.granblue.team/saved" /> <meta property="og:url" content="https://app.granblue.team/saved" />
@ -268,39 +290,136 @@ const SavedRoute: React.FC = () => {
onFilter={receiveFilters} onFilter={receiveFilters}
scrolled={scrolled} scrolled={scrolled}
element={element} element={element}
raidSlug={ (raidSlug) ? raidSlug : undefined } raidSlug={raidSlug ? raidSlug : undefined}
recency={recency}> recency={recency}
<h1>{t('saved.title')}</h1> >
<h1>{t("saved.title")}</h1>
</FilterBar> </FilterBar>
<section> <section>
<InfiniteScroll <InfiniteScroll
dataLength={ (parties && parties.length > 0) ? parties.length : 0} dataLength={parties && parties.length > 0 ? parties.length : 0}
next={() => setCurrentPage(currentPage + 1)} next={() => setCurrentPage(currentPage + 1)}
hasMore={totalPages > currentPage} hasMore={totalPages > currentPage}
loader={ <div id="NotFound"><h2>Loading...</h2></div> }> loader={
<GridRepCollection loading={loading}> <div id="NotFound">
{ renderParties() } <h2>Loading...</h2>
</GridRepCollection> </div>
}
>
<GridRepCollection>{renderParties()}</GridRepCollection>
</InfiniteScroll> </InfiniteScroll>
{ (parties.length == 0) ? {parties.length == 0 ? (
<div id="NotFound"> <div id="NotFound">
<h2>{ (loading) ? t('saved.loading') : t('saved.not_found') }</h2> <h2>{t("saved.not_found")}</h2>
</div> </div>
: '' } ) : (
""
)}
</section> </section>
</div> </div>
) )
} }
export async function getStaticProps({ locale }: { locale: string }) { 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 } }) => {
// Cookies
const cookie = getCookie("account", { req, res })
const accountData: AccountCookie = cookie
? JSON.parse(cookie as string)
: null
const headers = accountData
? { headers: { Authorization: `Bearer ${accountData.token}` } }
: {}
let { raids, sortedRaids } = await api.endpoints.raids
.getAll(headers)
.then((response) => organizeRaids(response.data.map((r: any) => r.raid)))
// Extract recency filter
const recencyParam: number = parseInt(query.recency)
// Extract element filter
const elementParam: string = query.element
const teamElement: TeamElement | undefined =
elementParam === "all"
? allElement
: elements.find(
(element) => element.name.en.toLowerCase() === elementParam
)
// Extract raid filter
const raidParam: string = query.raid
const raid: Raid | undefined = raids.find((r) => r.slug === raidParam)
// Create filter object
const filters: {
raid?: string
element?: number
recency?: number
} = {}
if (recencyParam) filters.recency = recencyParam
if (teamElement && teamElement.id > -1) filters.element = teamElement.id
if (raid) filters.raid = raid.id
// Fetch initial set of parties here
const response = await api.savedTeams({
params: filters,
...headers
})
return { return {
props: { props: {
...(await serverSideTranslations(locale, ['common'])), teams: response.data,
raids: raids,
sortedRaids: sortedRaids,
...(await serverSideTranslations(locale, ["common"])),
// Will be passed to the page component as props // 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 SavedRoute export default SavedRoute