From f59c569de442c2f1d804cbf9b1e547994d07be67 Mon Sep 17 00:00:00 2001 From: "Kalle (Sendou)" <38327916+Sendouc@users.noreply.github.com> Date: Thu, 26 Nov 2020 13:05:47 +0200 Subject: [PATCH] builds page weapon query param --- hooks/builds.ts | 27 ++++++++++++++++++++++++--- pages/builds/[[...slug]].tsx | 2 ++ 2 files changed, 26 insertions(+), 3 deletions(-) diff --git a/hooks/builds.ts b/hooks/builds.ts index 4f643cbde..432f622cb 100644 --- a/hooks/builds.ts +++ b/hooks/builds.ts @@ -1,6 +1,8 @@ import { Ability } from "@prisma/client"; import { abilities, isMainAbility } from "lib/lists/abilities"; import { weaponToCode } from "lib/lists/weaponCodes"; +import { weapons } from "lib/lists/weapons"; +import { useRouter } from "next/router"; import { GetBuildsByWeaponData } from "prisma/queries/getBuildsByWeapon"; import { Dispatch, useReducer } from "react"; import useSWR from "swr"; @@ -49,13 +51,17 @@ type Action = export type UseBuildsByWeaponDispatch = Dispatch; -// TODO: weapon in the URL - export function useBuildsByWeapon() { + const router = useRouter(); const [state, dispatch] = useReducer( (oldState: UseBuildsByWeaponState, action: Action) => { switch (action.type) { case "SET_WEAPON": + router.replace({ + pathname: "/builds", + query: { weapon: action.weapon }, + }); + return { ...oldState, weapon: action.weapon }; case "EXPAND_USER": return { @@ -109,9 +115,24 @@ export function useBuildsByWeapon() { return oldState; } }, - { weapon: "", filters: [], expandedUsers: new Set() as Set } + { + weapon: getInitialWeapon(), + filters: [], + expandedUsers: new Set() as Set, + } ); + function getInitialWeapon() { + if ( + typeof router.query.weapon !== "string" || + !weapons.includes(router.query.weapon as any) + ) { + return ""; + } + + return router.query.weapon; + } + const { data } = useSWR(() => { if (!state.weapon) return null; diff --git a/pages/builds/[[...slug]].tsx b/pages/builds/[[...slug]].tsx index 5c159ec0c..52b4a3144 100644 --- a/pages/builds/[[...slug]].tsx +++ b/pages/builds/[[...slug]].tsx @@ -10,6 +10,8 @@ import WeaponSelector from "components/common/WeaponSelector"; import { useBuildsByWeapon } from "hooks/builds"; import { useMyTheme } from "lib/useMyTheme"; +// TODO: button to add new build + const BuildsPage = () => { const { data,