Refactored CharacterGrid to pull its own data

This commit is contained in:
Justin Edmund 2022-02-03 23:51:23 -08:00
parent ef13369550
commit a5f64b6dbe

View file

@ -1,30 +1,22 @@
/* eslint-disable react-hooks/exhaustive-deps */ /* eslint-disable react-hooks/exhaustive-deps */
import React, { useCallback, useEffect, useMemo, useState } from 'react' import React, { useCallback, useContext, useEffect, useMemo, useState } from 'react'
import { useCookies } from 'react-cookie' import { useCookies } from 'react-cookie'
import { useModal as useModal } from '~utils/useModal' import { useModal as useModal } from '~utils/useModal'
import { AxiosResponse } from 'axios' import { AxiosResponse } from 'axios'
import debounce from 'lodash.debounce' import debounce from 'lodash.debounce'
import AppContext from '~context/AppContext'
import CharacterUnit from '~components/CharacterUnit' import CharacterUnit from '~components/CharacterUnit'
import SearchModal from '~components/SearchModal' import SearchModal from '~components/SearchModal'
import api from '~utils/api' import api from '~utils/api'
import './index.scss' import './index.scss'
// GridType
export enum GridType {
Class,
Character,
Weapon,
Summon
}
// Props // Props
interface Props { interface Props {
partyId?: string slug?: string
characters: GridArray<GridCharacter>
editable: boolean
createParty: () => Promise<AxiosResponse<any, any>> createParty: () => Promise<AxiosResponse<any, any>>
pushHistory?: (path: string) => void pushHistory?: (path: string) => void
} }
@ -44,6 +36,12 @@ const CharacterGrid = (props: Props) => {
// Set up state for party // Set up state for party
const [partyId, setPartyId] = useState('') const [partyId, setPartyId] = useState('')
// Set up state for view management
const [found, setFound] = useState(false)
const [loading, setLoading] = useState(true)
const [editable, setEditable] = useState(false)
const { setEditable: setEditableContext } = useContext(AppContext)
// Set up states for Grid data // Set up states for Grid data
const [characters, setCharacters] = useState<GridArray<GridCharacter>>({}) const [characters, setCharacters] = useState<GridArray<GridCharacter>>({})
@ -56,17 +54,16 @@ const CharacterGrid = (props: Props) => {
// Create a state dictionary to store pure objects for Search // Create a state dictionary to store pure objects for Search
const [searchGrid, setSearchGrid] = useState<GridArray<Character>>({}) const [searchGrid, setSearchGrid] = useState<GridArray<Character>>({})
// Set states from props // Fetch data from the server
useEffect(() => { useEffect(() => {
setPartyId(props.partyId || '') if (props.slug) fetchGrid(props.slug)
setCharacters(props.characters || {}) }, [])
}, [props])
// Initialize an array of current uncap values for each characters // Initialize an array of current uncap values for each characters
useEffect(() => { useEffect(() => {
let initialPreviousUncapValues: {[key: number]: number} = {} let initialPreviousUncapValues: {[key: number]: number} = {}
Object.values(props.characters).map(o => initialPreviousUncapValues[o.position] = o.uncap_level) Object.values(characters).map(o => initialPreviousUncapValues[o.position] = o.uncap_level)
setPreviousUncapValues(initialPreviousUncapValues) setPreviousUncapValues(initialPreviousUncapValues)
}, [props]) }, [props])
@ -76,6 +73,58 @@ const CharacterGrid = (props: Props) => {
setSearchGrid(newSearchGrid) setSearchGrid(newSearchGrid)
}, [characters]) }, [characters])
// Methods: Fetching an object from the server
async function fetchGrid(shortcode: string) {
return api.endpoints.parties.getOneWithObject({ id: shortcode, object: 'characters' })
.then(response => processResult(response))
.catch(error => processError(error))
}
function processResult(response: AxiosResponse) {
// Store the response
const party = response.data.party
// Get the party user and logged in user, if possible, to compare
const partyUser = (party.user_id) ? party.user_id : undefined
const loggedInUser = (cookies.user) ? cookies.user.user_id : ''
if (partyUser != undefined && loggedInUser != undefined && partyUser === loggedInUser) {
setEditable(true)
setEditableContext(true)
}
// Store the important party and state-keeping values
setPartyId(party.id)
setFound(true)
setLoading(false)
// Populate the weapons in state
populateCharacters(party.characters)
}
function processError(error: any) {
if (error.response != null) {
if (error.response.status == 404) {
setFound(false)
setLoading(false)
}
} else {
console.error(error)
}
}
function populateCharacters(list: [GridCharacter]) {
let characters: GridArray<GridCharacter> = {}
list.forEach((object: GridCharacter) => {
if (object.position != null)
characters[object.position] = object
})
setCharacters(characters)
}
// Methods: Adding an object from search // Methods: Adding an object from search
function openSearchModal(position: number) { function openSearchModal(position: number) {
setItemPositionForSearch(position) setItemPositionForSearch(position)
@ -200,8 +249,8 @@ const CharacterGrid = (props: Props) => {
return ( return (
<li key={`grid_unit_${i}`} > <li key={`grid_unit_${i}`} >
<CharacterUnit <CharacterUnit
gridCharacter={props.characters[i]} gridCharacter={characters[i]}
editable={props.editable} editable={editable}
position={i} position={i}
onClick={() => { openSearchModal(i) }} onClick={() => { openSearchModal(i) }}
updateUncap={initiateUncapUpdate} updateUncap={initiateUncapUpdate}