Skip to content

Commit

Permalink
some performance optimizations:
Browse files Browse the repository at this point in the history
  • Loading branch information
jaaimino committed Oct 30, 2024
1 parent d8dc5b7 commit 761eef4
Show file tree
Hide file tree
Showing 8 changed files with 79 additions and 45 deletions.
33 changes: 22 additions & 11 deletions src/hooks/use-api/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,28 +3,39 @@ import React from "react";

export const API_PATH = "https://ktdash.app/api";

export function useAPI() {
const request = React.useCallback((endpoint, content) => {
return fetch(`${API_PATH}${endpoint}`, {
credentials: "include",
method: "GET",
...content
}).then(response => response.json()).catch(e => console.log(e));
}, [])
return { request }
export const request = (endpoint, content) => {
console.log('requesting', endpoint);
return fetch(`${API_PATH}${endpoint}`, {
credentials: "include",
method: "GET",
...content
}).then(response => response.json()).catch(e => console.log(e));
}
export const requestJson = (endpoint, content) => {
return fetch(`${API_PATH}${endpoint}`, {
credentials: "include",
method: "GET",
...content
}).then(response => response.json()).catch(e => console.log(e));
}
export const requestText = (endpoint, content) => {
return fetch(`${API_PATH}${endpoint}`, {
credentials: "include",
method: "GET",
...content
}).then(response => response.text()).catch(e => console.log(e));
}

export function useRequest(endpoint, content, fetchCondition) {
const [data, setData] = React.useState(null);
const [error, setError] = React.useState(null);
const [isFetching, setIsFetching] = React.useState(false);
const api = useAPI();
React.useEffect(() => {
if (!isNil(fetchCondition) && !fetchCondition) {
return;
}
setIsFetching(true);
api.request(endpoint, content).then((data) => {
request(endpoint, content).then((data) => {
setData(data);
setIsFetching(false);
}).catch((e) => {
Expand Down
11 changes: 5 additions & 6 deletions src/hooks/use-auth/index.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
import React from "react";
import { useAPI } from "../use-api";
import { request } from "../use-api";
import { useLocalStorage } from "@mantine/hooks";

export default function useAuth() {
const api = useAPI();
const [user, setUser] = useLocalStorage({ key: 'auth' });

React.useEffect(() => {
Expand All @@ -16,14 +15,14 @@ export default function useAuth() {
}, []);

const getSession = async () => {
const auth = await api.request('/session.php', {
const auth = await request('/session.php', {
method: "GET"
});
return auth;
}

const signup = async (username, password, confirmpassword) => {
const auth = await api.request('/user.php', {
const auth = await request('/user.php', {
method: "POST",
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
Expand All @@ -39,7 +38,7 @@ export default function useAuth() {
}

const login = async (username, password) => {
const auth = await api.request('/session.php', {
const auth = await request('/session.php', {
method: "POST",
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
Expand All @@ -54,7 +53,7 @@ export default function useAuth() {
}

const logout = async () => {
const auth = await api.request('/session.php', {
const auth = await request('/session.php', {
method: "DELETE"
});
setUser(undefined);
Expand Down
21 changes: 10 additions & 11 deletions src/pages/dashboard/index.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { useLocation } from "wouter";
import { useAPI, useRequest } from "../../hooks/use-api";
import { request, useRequest } from "../../hooks/use-api";
import { ActionIcon, Card, Container, Group, LoadingOverlay, SimpleGrid, Stack, Tabs, Title } from "@mantine/core";
import OperativeCard from "../../components/operative-card";
import React from "react";
Expand All @@ -18,7 +18,6 @@ import useWindowDimensions from "../../hooks/get-window-dimensions";

export default function Dashboard() {
const { user: userData } = useAuth();
const api = useAPI();
const { appState, setAppState } = useAppContext();
const [dashboardRosterId] = useLocalStorage({ key: 'dashboardrosterid' });
const { data: roster, isFetching: isFetchinigTeam, setData: setRoster } = useRequest(`/roster.php?rid=${dashboardRosterId}&loadrosterdetail=1`, {}, !!dashboardRosterId);
Expand Down Expand Up @@ -60,15 +59,15 @@ export default function Dashboard() {
ployids: ""
});
roster.operatives.forEach((op) => {
api.request(`/rosteroperative.php`, {
request(`/rosteroperative.php`, {
method: "POST",
body: JSON.stringify({
...op,
curW: op.W
})
})
})
api.request(`/roster.php`, {
request(`/roster.php`, {
method: "POST",
body: JSON.stringify(updatedRoster)
})
Expand All @@ -89,7 +88,7 @@ export default function Dashboard() {
// Only send requests for operatives we actually toggled
if (oldOperatives[op.rosteropid].hidden !== op.hidden) {
opCount += 1;
api.request(`/rosteroperative.php`, {
request(`/rosteroperative.php`, {
method: "POST",
body: JSON.stringify(op)
})
Expand All @@ -113,7 +112,7 @@ export default function Dashboard() {
}, [roster, isSmallScreen]);
// eslint-disable-next-line react-hooks/exhaustive-deps
const handleSaveUpdateRoster = React.useCallback(debounce((newRoster) => {
api.request(`/roster.php`, {
request(`/roster.php`, {
method: "POST",
body: JSON.stringify(newRoster)
})
Expand Down Expand Up @@ -173,7 +172,7 @@ export default function Dashboard() {
...roster,
...newRoster
});
api.request(`/roster.php`, {
request(`/roster.php`, {
method: "POST",
body: JSON.stringify(newRoster)
})
Expand All @@ -192,7 +191,7 @@ export default function Dashboard() {
...roster,
tacops: [...roster.tacops.map((op) => op.tacopid === tacop.tacopid ? tacop : op)]
});
api.request(`/rostertacop.php`, {
request(`/rostertacop.php`, {
method: !!tacop.active ? "POST" : "DELETE",
body: JSON.stringify(newTacOp)
})
Expand All @@ -211,7 +210,7 @@ export default function Dashboard() {
...roster,
rostereqs: [...roster?.rostereqs?.map((eq) => eq.eqid === equipment.eqid ? ({ ...eq, selected: 1 }) : eq)]
});
api.request(`/rostereq.php`, {
request(`/rostereq.php`, {
method: "POST",
body: JSON.stringify(newEq)
})
Expand All @@ -220,15 +219,15 @@ export default function Dashboard() {
...roster,
rostereqs: [...roster?.rostereqs?.map((eq) => eq.eqid === equipment.eqid ? ({ ...eq, selected: 0 }) : eq)]
});
api.request(`/rostereq.php`, {
request(`/rostereq.php`, {
method: "DELETE",
body: JSON.stringify(newEq)
})
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [roster]);
const handleUpdateOperativeWounds = React.useCallback((operative, wounds) => {
api.request(`/rosteropw.php?roid=${operative.rosteropid}&curW=${wounds}`, {
request(`/rosteropw.php?roid=${operative.rosteropid}&curW=${wounds}`, {
method: "POST"
}).then((data) => {
if (data?.success) {
Expand Down
1 change: 0 additions & 1 deletion src/pages/dashboard/modals/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,6 @@ export function SelectOperativesModal(props) {
<SimpleGrid cols={{ base: 1, sm: 2 }}>
{operatives.map((operative) => (
<MiniOperativeCard operative={operative} onChange={handleUpdateOperative} />

))}
</SimpleGrid>
<Group justify="flex-end">
Expand Down
13 changes: 6 additions & 7 deletions src/pages/roster/index.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Link, useLocation, useRoute } from "wouter";
import { API_PATH, useAPI, useRequest } from "../../hooks/use-api";
import { API_PATH, request, useRequest } from "../../hooks/use-api";
import { Container, Group, Image, LoadingOverlay, SimpleGrid, Stack, Text, Title } from "@mantine/core";
import OperativeCard from "../../components/operative-card";
import React from "react";
Expand All @@ -14,7 +14,6 @@ import useWindowDimensions from "../../hooks/get-window-dimensions";

export default function Roster() {
const { user: userData } = useAuth();
const api = useAPI();
const { appState, setAppState } = useAppContext();
const [, params] = useRoute("/r/:rosterId");
const { data: roster, setData: setRoster, isFetching: isFetchinigTeam } = useRequest(`/roster.php?rid=${params?.rosterId}&loadrosterdetail=1`);
Expand All @@ -32,7 +31,7 @@ export default function Roster() {
),
});
const handleUpdateRoster = (roster) => {
api.request("/roster.php", {
request("/roster.php", {
method: "POST",
body: JSON.stringify(roster)
}).then((data) => {
Expand All @@ -54,7 +53,7 @@ export default function Roster() {
"eqids": operative?.equipments?.map((equip) => equip.eqid).join(","),
"notes": operative.notes
}
api.request("/rosteroperative.php", {
request("/rosteroperative.php", {
method: "POST",
body: JSON.stringify(newOperative)
}).then((data) => {
Expand Down Expand Up @@ -85,7 +84,7 @@ export default function Roster() {
"eqids": operative?.equipments?.map((equip) => equip.eqid).join(","),
"notes": operative.notes
}
api.request("/rosteroperative.php", {
request("/rosteroperative.php", {
method: "POST",
body: JSON.stringify(updatedOperative)
}).then((data) => {
Expand All @@ -112,7 +111,7 @@ export default function Roster() {
});
};
const handleDeleteOperative = (operative) => {
api.request(`/rosteroperative.php?roid=${operative.rosteropid}`, {
request(`/rosteroperative.php?roid=${operative.rosteropid}`, {
method: "DELETE"
}).then((data) => {
if (data?.success) {
Expand Down Expand Up @@ -140,7 +139,7 @@ export default function Roster() {
});
};
const handleDeleteRoster = () => {
api.request(`/roster.php?rid=${roster.rosterid}`, {
request(`/roster.php?rid=${roster.rosterid}`, {
method: "DELETE"
}).then((data) => {
if (data?.success) {
Expand Down
29 changes: 25 additions & 4 deletions src/pages/roster/modals/index.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
import { TextInput, Stack, Button, Group, Select, Table, SimpleGrid, Text, Checkbox, Textarea, LoadingOverlay, Box } from '@mantine/core';
import { useRequest } from '../../../hooks/use-api';
import { TextInput, Stack, Button, Group, Select, Table, SimpleGrid, Text, Checkbox, Textarea, LoadingOverlay, Box, ActionIcon } from '@mantine/core';
import { requestText, useRequest } from '../../../hooks/use-api';
import { modals } from '@mantine/modals';
import React from 'react';
import { flatten, groupBy, keyBy } from 'lodash';
import { convertShapes } from '../../../utils/shapes';
import { IconArrowForward, IconCrosshair, IconDice, IconDroplet, IconShield, IconSwords, IconTriangleInverted, IconUser } from '@tabler/icons-react';
import { IconArrowForward, IconCrosshair, IconDice, IconDroplet, IconRefresh, IconShield, IconSwords, IconTriangleInverted, IconUser } from '@tabler/icons-react';
import useAuth from '../../../hooks/use-auth';
import { useForm } from '@mantine/form';
import { useLocalStorage } from '@mantine/hooks';
import { DEFAULT_SETTINGS } from '../../settings';

export function UpdateRosterModal(props) {
const { onClose, roster } = props;
Expand Down Expand Up @@ -116,7 +118,7 @@ const Weapon = (props) => {
return (
<>
<Table.Tr key={weapon.wepid}>
<Table.Td style={{ width: '30px'}}>
<Table.Td style={{ width: '30px' }}>
<Checkbox
checked={checked}
onChange={(event) => onCheck(weapon.wepid, event.currentTarget.checked)}
Expand Down Expand Up @@ -144,6 +146,7 @@ const Weapon = (props) => {
export function OperativeModal(props) {
const { onClose, roster, operative: existingOperative } = props;
const modalId = existingOperative ? 'edit-operative' : 'add-operative';
const [settings] = useLocalStorage({ key: 'settings', defaultValue: DEFAULT_SETTINGS });
const [operativeData, setOperativeData] = React.useState(existingOperative);
const [operativeId, setOperativeId] = React.useState(existingOperative?.opid);
const { data: killteam, isFetching: isFetchingTeam } = useRequest(`/killteam.php?fa=${roster?.factionid}&kt=${roster?.killteamid}`);
Expand All @@ -154,6 +157,20 @@ export function OperativeModal(props) {
}));
const hiddenKT24Equipment = new Set(['Equipment', 'Universal Equipment']);

const setRandomOperativeName = async (opData) => {
if (!opData) {
return;
}
const randomName = await requestText(`/name.php?factionid=${opData.factionid}&killteamid=${opData.killteamid}&fireteamid=${opData.fireteamid}&opid=${opData.opid}`);
console.log(randomName);
if (randomName) {
setOperativeData({
...opData,
opname: randomName
})
}
}

const filterEquipment = (equipCategory) => {
if (killteam?.edition === "kt24") {
return !hiddenKT24Equipment.has(equipCategory)
Expand Down Expand Up @@ -202,11 +219,15 @@ export function OperativeModal(props) {
...operatives[operativeId],
weapons: []
});
if (settings.useoptypeasname !== "y") {
setRandomOperativeName(operatives[operativeId]);
}
}}
/>}
<TextInput
label="Operative Name"
placeholder="Operative Name"
rightSection={settings.useoptypeasname === "y" ? <></> : <ActionIcon onClick={() => setRandomOperativeName(operativeData)}><IconRefresh /></ActionIcon>}
value={operativeData?.opname}
onChange={(e) => {
setOperativeData({
Expand Down
7 changes: 3 additions & 4 deletions src/pages/rosters/index.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import React from "react";
import { Container, LoadingOverlay, SimpleGrid, Text, Title } from "@mantine/core";

import { useAPI, useRequest } from "../../hooks/use-api";
import { request, useRequest } from "../../hooks/use-api";
import { useLocation, useRoute } from "wouter";
import RosterCard from "../../components/roster-card";
import { useAppContext } from "../../hooks/app-context";
Expand All @@ -13,7 +13,6 @@ import { useLocalStorage } from "@mantine/hooks";
import { notifications } from "@mantine/notifications";

export default function Rosters() {
const api = useAPI();
const [, navigate] = useLocation();
const { user: userData } = useAuth();
const { appState, setAppState } = useAppContext();
Expand All @@ -24,7 +23,7 @@ export default function Rosters() {
const rosters = user?.rosters ?? [];

const handleCreateRoster = (roster) => {
api.request("/roster.php", {
request("/roster.php", {
method: "POST",
body: JSON.stringify(roster)
}).then((data) => {
Expand All @@ -39,7 +38,7 @@ export default function Rosters() {
}

const handleDeleteRoster = (roster) => {
api.request(`/roster.php?rid=${roster.rosterid}`, {
request(`/roster.php?rid=${roster.rosterid}`, {
method: "DELETE"
}).then((data) => {
if (data?.success) {
Expand Down
9 changes: 8 additions & 1 deletion src/pages/rosters/modals/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,12 @@ import { useRequest } from '../../../hooks/use-api';
import { modals } from '@mantine/modals';
import React from 'react';
import useAuth from '../../../hooks/use-auth';
import { useLocalStorage } from '@mantine/hooks';
import { DEFAULT_SETTINGS } from '../../settings';

export function AddRosterModal(props) {
const { onClose } = props;
const [settings] = useLocalStorage({ key: 'settings', defaultValue: DEFAULT_SETTINGS });
const { user } = useAuth();
const form = useForm({
mode: 'controlled',
Expand All @@ -21,7 +24,11 @@ export function AddRosterModal(props) {
team: (value) => (!value ? 'Must select a team' : null),
},
});
const { data: factions } = useRequest("/faction.php?loadkts=1");
const teamParams = new URLSearchParams({
loadkts: 1,
edition: settings.edition
}).toString();
const { data: factions } = useRequest(`/faction.php?${teamParams}`, {}, !!settings);

React.useEffect(() => {
form.setFieldValue('team', null);
Expand Down

0 comments on commit 761eef4

Please sign in to comment.