Query params work on Saved and Profile pages

This commit is contained in:
Justin Edmund 2022-03-07 18:14:05 -08:00
parent 1d98f13dee
commit fa73a4bd7d
2 changed files with 236 additions and 98 deletions

View file

@ -1,50 +1,97 @@
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 { useCookies } from 'react-cookie'
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 { serverSideTranslations } from 'next-i18next/serverSideTranslations' import { serverSideTranslations } from 'next-i18next/serverSideTranslations'
import api from '~utils/api' import api from '~utils/api'
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 emptyUser = {
id: '',
username: '',
granblueId: 0,
picture: {
picture: '',
element: ''
},
private: false
}
const ProfileRoute: React.FC = () => { const ProfileRoute: React.FC = () => {
// Set up cookies
const [cookies] = useCookies(['account'])
const headers = (cookies.account) ? {
headers: {
'Authorization': `Bearer ${cookies.account.access_token}`
}
} : {}
// Set up router
const router = useRouter() const router = useRouter()
const { username } = router.query const { username } = router.query
// Import translations
const { t } = useTranslation('common') const { t } = useTranslation('common')
const [cookies] = useCookies(['account'])
// Set up app-specific states
const [found, setFound] = useState(false) const [found, setFound] = useState(false)
const [loading, setLoading] = useState(true) const [loading, setLoading] = useState(true)
const [raidsLoading, setRaidsLoading] = useState(true)
const [scrolled, setScrolled] = useState(false) const [scrolled, setScrolled] = useState(false)
// Set up page-specific states
const [parties, setParties] = useState<Party[]>([]) const [parties, setParties] = useState<Party[]>([])
const [user, setUser] = useState<User>({ const [raids, setRaids] = useState<Raid[]>()
id: '', const [raid, setRaid] = useState<Raid>()
username: '', const [user, setUser] = useState<User>(emptyUser)
granblueId: 0,
picture: { // Set up filter-specific query states
picture: '', // Recency is in seconds
element: '' const [element, setElement] = useQueryState("element", {
}, defaultValue: -1,
private: false parse: (query: string) => parseElement(query),
serialize: value => serializeElement(value)
}) })
const [raidSlug, setRaidSlug] = useQueryState("raid", { defaultValue: "all" })
const [recency, setRecency] = useQueryState("recency", queryTypes.integer.withDefault(-1))
// Filter states // Define transformers for element
const [element, setElement] = useState<number | null>(null) function parseElement(query: string) {
const [raidId, setRaidId] = useState<string | null>(null) let element: TeamElement | undefined =
const [recencyInSeconds, setRecencyInSeconds] = useState<number | null>(null) (query === 'all') ?
allElement : elements.find(element => element.name.en.toLowerCase() === query)
return (element) ? element.id : -1
}
function serializeElement(value: number | undefined) {
let name = ''
if (value != undefined) {
if (value == -1)
name = allElement.name.en.toLowerCase()
else
name = elements[value].name.en.toLowerCase()
}
return name
}
// 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
const handleError = useCallback((error: any) => { const handleError = useCallback((error: any) => {
if (error.response != null) { if (error.response != null) {
console.error(error) console.error(error)
@ -56,24 +103,14 @@ const ProfileRoute: React.FC = () => {
const fetchProfile = useCallback(() => { const fetchProfile = useCallback(() => {
const filters = { const filters = {
params: { params: {
element: element, element: (element != -1) ? element : undefined,
raid: raidId, raid: (raid) ? raid.id : undefined,
recency: recencyInSeconds recency: (recency != -1) ? recency : undefined
} }
} }
const headers = (cookies.account) ? { if (username && !Array.isArray(username))
headers: { api.endpoints.users.getOne({ id: username , params: {...filters, ...headers} })
'Authorization': `Bearer ${cookies.account.access_token}`
}
} : {}
const params = {...filters, ...headers}
setLoading(true)
if (username)
api.endpoints.users.getOne({ id: username as string, params: params })
.then(response => { .then(response => {
setUser({ setUser({
id: response.data.user.id, id: response.data.user.id,
@ -91,29 +128,55 @@ const ProfileRoute: React.FC = () => {
setLoading(false) setLoading(false)
}) })
.catch(error => handleError(error)) .catch(error => handleError(error))
}, [username, element, raidId, recencyInSeconds, cookies.account, handleError]) }, [element, raid, recency])
// Fetch all raids on mount, then find the raid in the URL if present
useEffect(() => { useEffect(() => {
fetchProfile() api.endpoints.raids.getAll()
}, [fetchProfile]) .then(response => {
const cleanRaids: Raid[] = response.data.map((r: any) => r.raid)
setRaids(cleanRaids)
function receiveFilters(element?: number, raid?: string, recency?: number) { setRaidsLoading(false)
if (element != null && element >= 0)
const raid = cleanRaids.find(r => r.slug === raidSlug)
setRaid(raid)
return raid
})
}, [setRaids])
// When the element, raid or recency filter changes,
// fetch all teams again.
useEffect(() => {
if (!raidsLoading) fetchProfile()
}, [element, raid, recency])
// On first mount only, disable loading if we are fetching all teams
useEffect(() => {
if (raidSlug === 'all') {
setRaidsLoading(false)
fetchProfile()
}
}, [])
// Receive filters from the filter bar
function receiveFilters({ element, raidSlug, recency }: {element?: number, raidSlug?: string, recency?: number}) {
if (element == 0)
setElement(0)
else if (element)
setElement(element) setElement(element)
else
setElement(null)
if (raid && raid != '0') if (raids && raidSlug) {
setRaidId(raid) const raid = raids.find(raid => raid.slug === raidSlug)
else setRaid(raid)
setRaidId(null) setRaidSlug(raidSlug)
}
if (recency && recency > 0) if (recency) setRecency(recency)
setRecencyInSeconds(recency)
else
setRecencyInSeconds(null)
} }
// Methods: Navigation
function handleScroll() { function handleScroll() {
if (window.pageYOffset > 90) if (window.pageYOffset > 90)
setScrolled(true) setScrolled(true)
@ -125,6 +188,8 @@ const ProfileRoute: React.FC = () => {
router.push(`/p/${shortcode}`) router.push(`/p/${shortcode}`)
} }
// TODO: Add save functions
return ( return (
<div id="Profile"> <div id="Profile">
<Head> <Head>
@ -140,17 +205,22 @@ const ProfileRoute: React.FC = () => {
<meta name="twitter:title" content={`@${user.username}\'s Teams`} /> <meta name="twitter:title" content={`@${user.username}\'s Teams`} />
<meta name="twitter:description" content={`Browse @${user.username}\''s Teams and filter raid, element or recency`} /> <meta name="twitter:description" content={`Browse @${user.username}\''s Teams and filter raid, element or recency`} />
</Head> </Head>
<FilterBar onFilter={receiveFilters} scrolled={scrolled}> <FilterBar
<div className="UserInfo"> onFilter={receiveFilters}
<img scrolled={scrolled}
alt={user.picture.picture} element={element}
className={`profile ${user.picture.element}`} raidSlug={ (raidSlug) ? raidSlug : undefined }
srcSet={`/profile/${user.picture.picture}.png, recency={recency}>
/profile/${user.picture.picture}@2x.png 2x`} <div className="UserInfo">
src={`/profile/${user.picture.picture}.png`} <img
/> alt={user.picture.picture}
<h1>{user.username}</h1> className={`profile ${user.picture.element}`}
</div> srcSet={`/profile/${user.picture.picture}.png,
/profile/${user.picture.picture}@2x.png 2x`}
src={`/profile/${user.picture.picture}.png`}
/>
<h1>{user.username}</h1>
</div>
</FilterBar> </FilterBar>
<section> <section>

View file

@ -1,43 +1,84 @@
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 { useCookies } from 'react-cookie'
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 clonedeep from 'lodash.clonedeep'
import { serverSideTranslations } from 'next-i18next/serverSideTranslations' import { serverSideTranslations } from 'next-i18next/serverSideTranslations'
import clonedeep from 'lodash.clonedeep'
import api from '~utils/api' import api from '~utils/api'
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 = () => { const SavedRoute: React.FC = () => {
const router = useRouter() // Set up cookies
const { t } = useTranslation('common')
// Cookies
const [cookies] = useCookies(['account']) const [cookies] = useCookies(['account'])
const headers = (cookies.account != null) ? { const headers = (cookies.account) ? {
'Authorization': `Bearer ${cookies.account.access_token}` headers: {
'Authorization': `Bearer ${cookies.account.access_token}`
}
} : {} } : {}
// Set up router
const router = useRouter()
// Import translations
const { t } = useTranslation('common')
// Set up app-specific states
const [loading, setLoading] = useState(true) const [loading, setLoading] = useState(true)
const [raidsLoading, setRaidsLoading] = useState(true)
const [scrolled, setScrolled] = useState(false) const [scrolled, setScrolled] = useState(false)
// Set up page-specific states
const [parties, setParties] = useState<Party[]>([]) const [parties, setParties] = useState<Party[]>([])
const [raids, setRaids] = useState<Raid[]>()
const [raid, setRaid] = useState<Raid>()
// Filter states // Set up filter-specific query states
const [element, setElement] = useState<number | null>(null) // Recency is in seconds
const [raidId, setRaidId] = useState<string | null>(null) const [element, setElement] = useQueryState("element", {
const [recencyInSeconds, setRecencyInSeconds] = useState<number | null>(null) defaultValue: -1,
parse: (query: string) => parseElement(query),
serialize: value => serializeElement(value)
})
const [raidSlug, setRaidSlug] = useQueryState("raid", { defaultValue: "all" })
const [recency, setRecency] = useQueryState("recency", queryTypes.integer.withDefault(-1))
// Define transformers for element
function parseElement(query: string) {
let element: TeamElement | undefined =
(query === 'all') ?
allElement : elements.find(element => element.name.en.toLowerCase() === query)
return (element) ? element.id : -1
}
function serializeElement(value: number | undefined) {
let name = ''
if (value != undefined) {
if (value == -1)
name = allElement.name.en.toLowerCase()
else
name = elements[value].name.en.toLowerCase()
}
return name
}
// 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
const handleError = useCallback((error: any) => { const handleError = useCallback((error: any) => {
if (error.response != null) { if (error.response != null) {
console.error(error) console.error(error)
@ -47,51 +88,73 @@ const SavedRoute: React.FC = () => {
}, []) }, [])
const fetchTeams = useCallback(() => { const fetchTeams = useCallback(() => {
const filterParams = { const filters = {
params: { params: {
element: element, element: (element != -1) ? element : undefined,
raid: raidId, raid: (raid) ? raid?.id : undefined,
recency: recencyInSeconds recency: (recency != -1) ? recency : undefined
},
headers: {
'Authorization': `Bearer ${cookies.account.access_token}`
} }
} }
setLoading(true) api.savedTeams({...filters, ...headers})
api.savedTeams(filterParams)
.then(response => { .then(response => {
const parties: Party[] = response.data const parties: Party[] = response.data
setParties(parties.map((p: any) => p.party).sort((a, b) => (a.created_at > b.created_at) ? -1 : 1)) setParties(parties.map((p: any) => p.party)
.sort((a, b) => (a.created_at > b.created_at) ? -1 : 1))
}) })
.then(() => { .then(() => {
setLoading(false) setLoading(false)
}) })
.catch(error => handleError(error)) .catch(error => handleError(error))
}, [element, raidId, recencyInSeconds, cookies.account, handleError]) }, [element, raid, recency])
// Fetch all raids on mount, then find the raid in the URL if present
useEffect(() => { useEffect(() => {
fetchTeams() api.endpoints.raids.getAll()
}, [fetchTeams]) .then(response => {
const cleanRaids: Raid[] = response.data.map((r: any) => r.raid)
setRaids(cleanRaids)
function receiveFilters(element?: number, raid?: string, recency?: number) { setRaidsLoading(false)
if (element != null && element >= 0)
const raid = cleanRaids.find(r => r.slug === raidSlug)
setRaid(raid)
return raid
})
}, [setRaids])
// When the element, raid or recency filter changes,
// fetch all teams again.
useEffect(() => {
if (!raidsLoading) fetchTeams()
}, [element, raid, recency])
// On first mount only, disable loading if we are fetching all teams
useEffect(() => {
if (raidSlug === 'all') {
setRaidsLoading(false)
fetchTeams()
}
}, [])
// Receive filters from the filter bar
function receiveFilters({ element, raidSlug, recency }: {element?: number, raidSlug?: string, recency?: number}) {
if (element == 0)
setElement(0)
else if (element)
setElement(element) setElement(element)
else
setElement(null)
if (raid && raid != '0') if (raids && raidSlug) {
setRaidId(raid) const raid = raids.find(raid => raid.slug === raidSlug)
else setRaid(raid)
setRaidId(null) setRaidSlug(raidSlug)
}
if (recency && recency > 0) if (recency) setRecency(recency)
setRecencyInSeconds(recency)
else
setRecencyInSeconds(null)
} }
// Methods: Favorites
function toggleFavorite(teamId: string, favorited: boolean) { function toggleFavorite(teamId: string, favorited: boolean) {
if (favorited) if (favorited)
unsaveFavorite(teamId) unsaveFavorite(teamId)
@ -133,6 +196,7 @@ const SavedRoute: React.FC = () => {
}) })
} }
// Methods: Navigation
function handleScroll() { function handleScroll() {
if (window.pageYOffset > 90) if (window.pageYOffset > 90)
setScrolled(true) setScrolled(true)
@ -158,8 +222,13 @@ const SavedRoute: React.FC = () => {
<meta name="twitter:title" content="Your saved Teams" /> <meta name="twitter:title" content="Your saved Teams" />
</Head> </Head>
<FilterBar onFilter={receiveFilters} scrolled={scrolled}> <FilterBar
<h1>{t('saved.title')}</h1> onFilter={receiveFilters}
scrolled={scrolled}
element={element}
raidSlug={ (raidSlug) ? raidSlug : undefined }
recency={recency}>
<h1>{t('saved.title')}</h1>
</FilterBar> </FilterBar>
<section> <section>
@ -178,8 +247,7 @@ const SavedRoute: React.FC = () => {
key={`party-${i}`} key={`party-${i}`}
displayUser={true} displayUser={true}
onClick={goTo} onClick={goTo}
onSave={toggleFavorite} onSave={toggleFavorite} />
/>
}) })
} }
</GridRepCollection> </GridRepCollection>