Merge pull request #16 from jedmund/react-cleanup

Cleanup React warnings and fix multiple API calls
This commit is contained in:
Justin Edmund 2022-02-28 13:00:13 -08:00 committed by GitHub
commit bcccfb409a
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
5 changed files with 149 additions and 120 deletions

View file

@ -1,4 +1,4 @@
import React, { useEffect, useState } from 'react' import React, { useCallback, useEffect, useMemo, useState } from 'react'
import { useSnapshot } from 'valtio' import { useSnapshot } from 'valtio'
import { useCookies } from 'react-cookie' import { useCookies } from 'react-cookie'
import clonedeep from 'lodash.clonedeep' import clonedeep from 'lodash.clonedeep'
@ -24,12 +24,12 @@ interface Props {
const Party = (props: Props) => { const Party = (props: Props) => {
// Cookies // Cookies
const [cookies, _] = useCookies(['user']) const [cookies] = useCookies(['user'])
const headers = (cookies.user != null) ? { const headers = useMemo(() => {
headers: { return (cookies.user != null) ? {
'Authorization': `Bearer ${cookies.user.access_token}` headers: { 'Authorization': `Bearer ${cookies.user.access_token}` }
} } : {}
} : {} }, [cookies.user])
// Set up states // Set up states
const { party } = useSnapshot(appState) const { party } = useSnapshot(appState)
@ -41,16 +41,6 @@ const Party = (props: Props) => {
appState.grid = resetState.grid appState.grid = resetState.grid
}, []) }, [])
// Fetch data from the server
useEffect(() => {
const shortcode = (props.slug) ? props.slug : undefined
if (shortcode)
fetchDetails(shortcode)
else
appState.party.editable = true
}, [props.slug, fetchDetails])
// Methods: Creating a new party // Methods: Creating a new party
async function createParty(extra: boolean = false) { async function createParty(extra: boolean = false) {
let body = { let body = {
@ -92,7 +82,6 @@ const Party = (props: Props) => {
appState.party.raid = raid appState.party.raid = raid
}) })
} }
} }
// Methods: Navigating with segmented control // Methods: Navigating with segmented control
@ -116,13 +105,7 @@ const Party = (props: Props) => {
} }
// Methods: Fetch party details // Methods: Fetch party details
function fetchDetails(shortcode: string) { const processResult = useCallback((response: AxiosResponse) => {
return api.endpoints.parties.getOne({ id: shortcode, params: headers })
.then(response => processResult(response))
.catch(error => processError(error))
}
function processResult(response: AxiosResponse) {
appState.party.id = response.data.party.id appState.party.id = response.data.party.id
appState.party.user = response.data.party.user appState.party.user = response.data.party.user
appState.party.favorited = response.data.party.favorited appState.party.favorited = response.data.party.favorited
@ -131,18 +114,32 @@ const Party = (props: Props) => {
appState.party.name = response.data.party.name appState.party.name = response.data.party.name
appState.party.description = response.data.party.description appState.party.description = response.data.party.description
appState.party.raid = response.data.party.raid appState.party.raid = response.data.party.raid
} }, [])
function processError(error: any) { const handleError = useCallback((error: any) => {
if (error.response != null) { if (error.response != null && error.response.status == 404) {
if (error.response.status == 404) { // setFound(false)
// setFound(false) } else if (error.response != null) {
// setLoading(false)
}
} else {
console.error(error) console.error(error)
} else {
console.error("There was an error.")
} }
} }, [])
const fetchDetails = useCallback((shortcode: string) => {
return api.endpoints.parties.getOne({ id: shortcode, params: headers })
.then(response => processResult(response))
.catch(error => handleError(error))
}, [headers, processResult, handleError])
useEffect(() => {
const shortcode = (props.slug) ? props.slug : undefined
if (shortcode)
fetchDetails(shortcode)
else
appState.party.editable = true
}, [props.slug, fetchDetails])
// Render: JSX components // Render: JSX components
const navigation = ( const navigation = (

View file

@ -1,4 +1,4 @@
import React, { useEffect, useState } from 'react' import React, { useCallback, useEffect, useState } from 'react'
import { useCookies } from 'react-cookie' import { useCookies } from 'react-cookie'
import { appState } from '~utils/appState' import { appState } from '~utils/appState'
@ -15,49 +15,18 @@ interface Props {
} }
const RaidDropdown = React.forwardRef<HTMLSelectElement, Props>(function useFieldSet(props, ref) { const RaidDropdown = React.forwardRef<HTMLSelectElement, Props>(function useFieldSet(props, ref) {
const [cookies, _] = useCookies(['user']) const [cookies] = useCookies(['user'])
const headers = (cookies.user != null) ? {
headers: { 'Authorization': `Bearer ${cookies.user.access_token}` }
} : {}
const [raids, setRaids] = useState<Raid[][]>() const [raids, setRaids] = useState<Raid[][]>()
const [flatRaids, setFlatRaids] = useState<Raid[]>()
const raidGroups = [ const raidGroups = [
'Assorted', 'Assorted', 'Omega', 'T1 Summons', 'T2 Summons',
'Omega', 'Primarchs', 'Nightmare', 'Omega (Impossible)', 'Omega II',
'T1 Summons', 'Tier 1 Summons (Impossible)', 'Tier 3 Summons', 'Ennead', 'Malice',
'T2 Summons', '6-Star Raids', 'Six-Dragons', 'Nightmare (Impossible)', 'Astral',
'Primarchs',
'Nightmare',
'Omega (Impossible)',
'Omega II',
'Tier 1 Summons (Impossible)',
'Tier 3 Summons',
'Ennead',
'Malice',
'6-Star Raids',
'Six-Dragons',
'Nightmare (Impossible)',
'Astral',
'Super Ultimate' 'Super Ultimate'
] ]
useEffect(() => { const organizeRaids = useCallback((raids: Raid[]) => {
fetchRaids()
}, [fetchRaids])
function fetchRaids() {
api.endpoints.raids.getAll(headers)
.then((response) => {
const raids = response.data.map((r: any) => r.raid)
appState.raids = raids
organizeRaids(raids)
})
}
function organizeRaids(raids: Raid[]) {
const numGroups = Math.max.apply(Math, raids.map(raid => raid.group)) const numGroups = Math.max.apply(Math, raids.map(raid => raid.group))
let groupedRaids = [] let groupedRaids = []
@ -78,7 +47,25 @@ const RaidDropdown = React.forwardRef<HTMLSelectElement, Props>(function useFiel
}) })
setRaids(groupedRaids) setRaids(groupedRaids)
} }, [props.allOption])
useEffect(() => {
const headers = (cookies.user != null) ? {
headers: { 'Authorization': `Bearer ${cookies.user.access_token}` }
} : {}
function fetchRaids() {
api.endpoints.raids.getAll(headers)
.then((response) => {
const raids = response.data.map((r: any) => r.raid)
appState.raids = raids
organizeRaids(raids)
})
}
fetchRaids()
}, [cookies.user, organizeRaids])
function raidGroup(index: number) { function raidGroup(index: number) {
const options = raids && raids.length > 0 && raids[index].length > 0 && const options = raids && raids.length > 0 && raids[index].length > 0 &&

View file

@ -21,7 +21,6 @@ const ProfileRoute: React.FC = () => {
}) })
useEffect(() => { useEffect(() => {
console.log(`Fetching profile for ${username}...`)
fetchProfile(username as string) fetchProfile(username as string)
}, [username]) }, [username])

View file

@ -1,4 +1,4 @@
import React, { useEffect, useState } from 'react' import React, { useCallback, useEffect, useState } from 'react'
import { useRouter } from 'next/router' import { useRouter } from 'next/router'
import { useCookies } from 'react-cookie' import { useCookies } from 'react-cookie'
import clonedeep from 'lodash.clonedeep' import clonedeep from 'lodash.clonedeep'
@ -13,7 +13,7 @@ const SavedRoute: React.FC = () => {
const router = useRouter() const router = useRouter()
// Cookies // Cookies
const [cookies, _] = useCookies(['user']) const [cookies] = useCookies(['user'])
const headers = (cookies.user != null) ? { const headers = (cookies.user != null) ? {
'Authorization': `Bearer ${cookies.user.access_token}` 'Authorization': `Bearer ${cookies.user.access_token}`
} : {} } : {}
@ -21,31 +21,41 @@ const SavedRoute: React.FC = () => {
const [found, setFound] = useState(false) const [found, setFound] = useState(false)
const [loading, setLoading] = useState(true) const [loading, setLoading] = useState(true)
const [scrolled, setScrolled] = useState(false) const [scrolled, setScrolled] = useState(false)
const [parties, setParties] = useState<Party[]>([]) const [parties, setParties] = useState<Party[]>([])
useEffect(() => { const [element, setElement] = useState<number | null>(null)
console.log(`Fetching favorite teams...`) const [raidId, setRaidId] = useState<string | null>(null)
fetchTeams() const [recencyInSeconds, setRecencyInSeconds] = useState<number | null>(null)
}, [fetchTeams])
useEffect(() => { useEffect(() => {
window.addEventListener("scroll", handleScroll) window.addEventListener("scroll", handleScroll)
return () => window.removeEventListener("scroll", handleScroll); return () => window.removeEventListener("scroll", handleScroll);
}, []) }, [])
async function fetchTeams(element?: number, raid?: string, recency?: number) { const handleError = useCallback((error: any) => {
const params = { if (error.response != null && error.response.status == 404) {
setFound(false)
} else if (error.response != null) {
console.error(error)
} else {
console.error("There was an error.")
}
}, [])
const fetchTeams = useCallback(() => {
const filterParams = {
params: { params: {
element: (element && element >= 0) ? element : undefined, element: element,
raid: (raid && raid != '0') ? raid : undefined, raid: raidId,
recency: (recency && recency > 0) ? recency : undefined recency: recencyInSeconds
}, },
headers: { headers: {
'Authorization': `Bearer ${cookies.user.access_token}` 'Authorization': `Bearer ${cookies.user.access_token}`
} }
} }
api.savedTeams(params) 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))
@ -54,15 +64,28 @@ const SavedRoute: React.FC = () => {
setFound(true) setFound(true)
setLoading(false) setLoading(false)
}) })
.catch(error => { .catch(error => handleError(error))
if (error.response != null) { }, [element, raidId, recencyInSeconds, cookies.user, handleError])
if (error.response.status == 404) {
setFound(false) useEffect(() => {
} fetchTeams()
} else { }, [fetchTeams])
console.error(error)
} function receiveFilters(element?: number, raid?: string, recency?: number) {
}) if (element != null && element >= 0)
setElement(element)
else
setElement(null)
if (raid && raid != '0')
setRaidId(raid)
else
setRaidId(null)
if (recency && recency > 0)
setRecencyInSeconds(recency)
else
setRecencyInSeconds(null)
} }
function toggleFavorite(teamId: string, favorited: boolean) { function toggleFavorite(teamId: string, favorited: boolean) {
@ -152,7 +175,7 @@ const SavedRoute: React.FC = () => {
return ( return (
<div id="Teams"> <div id="Teams">
<FilterBar onFilter={fetchTeams} name="Your saved teams" scrolled={scrolled} /> <FilterBar onFilter={receiveFilters} name="Your saved teams" scrolled={scrolled} />
{ (parties.length > 0) ? renderGrids() : renderNoGrids() } { (parties.length > 0) ? renderGrids() : renderNoGrids() }
</div> </div>
) )

View file

@ -1,4 +1,4 @@
import React, { useEffect, useState } from 'react' import React, { useCallback, useEffect, useState } from 'react'
import { useRouter } from 'next/router' import { useRouter } from 'next/router'
import { useCookies } from 'react-cookie' import { useCookies } from 'react-cookie'
import clonedeep from 'lodash.clonedeep' import clonedeep from 'lodash.clonedeep'
@ -13,7 +13,7 @@ const TeamsRoute: React.FC = () => {
const router = useRouter() const router = useRouter()
// Cookies // Cookies
const [cookies, _] = useCookies(['user']) const [cookies] = useCookies(['user'])
const headers = (cookies.user != null) ? { const headers = (cookies.user != null) ? {
'Authorization': `Bearer ${cookies.user.access_token}` 'Authorization': `Bearer ${cookies.user.access_token}`
} : {} } : {}
@ -21,31 +21,41 @@ const TeamsRoute: React.FC = () => {
const [found, setFound] = useState(false) const [found, setFound] = useState(false)
const [loading, setLoading] = useState(true) const [loading, setLoading] = useState(true)
const [scrolled, setScrolled] = useState(false) const [scrolled, setScrolled] = useState(false)
const [parties, setParties] = useState<Party[]>([]) const [parties, setParties] = useState<Party[]>([])
useEffect(() => { const [element, setElement] = useState<number | null>(null)
console.log(`Fetching teams...`) const [raidId, setRaidId] = useState<string | null>(null)
fetchTeams() const [recencyInSeconds, setRecencyInSeconds] = useState<number | null>(null)
}, [fetchTeams])
useEffect(() => { useEffect(() => {
window.addEventListener("scroll", handleScroll) window.addEventListener("scroll", handleScroll)
return () => window.removeEventListener("scroll", handleScroll); return () => window.removeEventListener("scroll", handleScroll);
}, []) }, [])
async function fetchTeams(element?: number, raid?: string, recency?: number) { const handleError = useCallback((error: any) => {
const params = { if (error.response != null && error.response.status == 404) {
setFound(false)
} else if (error.response != null) {
console.error(error)
} else {
console.error("There was an error.")
}
}, [])
const fetchTeams = useCallback(() => {
const filterParams = {
params: { params: {
element: (element && element >= 0) ? element : undefined, element: element,
raid: (raid && raid != '0') ? raid : undefined, raid: raidId,
recency: (recency && recency > 0) ? recency : undefined recency: recencyInSeconds
}, },
headers: { headers: {
'Authorization': `Bearer ${cookies.user.access_token}` 'Authorization': `Bearer ${cookies.user.access_token}`
} }
} }
api.endpoints.parties.getAll(params) api.endpoints.parties.getAll(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))
@ -54,15 +64,28 @@ const TeamsRoute: React.FC = () => {
setFound(true) setFound(true)
setLoading(false) setLoading(false)
}) })
.catch(error => { .catch(error => handleError(error))
if (error.response != null) { }, [element, raidId, recencyInSeconds, cookies.user, handleError])
if (error.response.status == 404) {
setFound(false) useEffect(() => {
} fetchTeams()
} else { }, [fetchTeams])
console.error(error)
} function receiveFilters(element?: number, raid?: string, recency?: number) {
}) if (element != null && element >= 0)
setElement(element)
else
setElement(null)
if (raid && raid != '0')
setRaidId(raid)
else
setRaidId(null)
if (recency && recency > 0)
setRecencyInSeconds(recency)
else
setRecencyInSeconds(null)
} }
function toggleFavorite(teamId: string, favorited: boolean) { function toggleFavorite(teamId: string, favorited: boolean) {
@ -152,7 +175,7 @@ const TeamsRoute: React.FC = () => {
return ( return (
<div id="Teams"> <div id="Teams">
<FilterBar onFilter={fetchTeams} name="Discover Teams" scrolled={scrolled} /> <FilterBar onFilter={receiveFilters} name="Discover Teams" scrolled={scrolled} />
{ (parties.length > 0) ? renderGrids() : renderNoGrids() } { (parties.length > 0) ? renderGrids() : renderNoGrids() }
</div> </div>
) )