From 717c2125c15df749b06e827cb588434aef155161 Mon Sep 17 00:00:00 2001 From: Antonio De Lucreziis Date: Thu, 24 Nov 2022 20:01:31 +0100 Subject: [PATCH] fix: route home for missing problems --- client/hooks.tsx | 6 +++--- client/pages/Problem.tsx | 14 ++++++-------- 2 files changed, 9 insertions(+), 11 deletions(-) diff --git a/client/hooks.tsx b/client/hooks.tsx index 255fbf2..eebaf52 100644 --- a/client/hooks.tsx +++ b/client/hooks.tsx @@ -40,10 +40,10 @@ type HeuristicStateUpdater = StateUpdater type ResourceHookFunction = ( url: string | (() => string), initialValue: T, - onError?: () => void + onValue?: (value: T) => void ) => [T, RefreshFunction, HeuristicStateUpdater] -export const useResource: ResourceHookFunction = (url, initialValue, onError) => { +export const useResource: ResourceHookFunction = (url, initialValue, onValue) => { const [value, setValue] = useState(initialValue) function refresh() { @@ -55,11 +55,11 @@ export const useResource: ResourceHookFunction = (url, initialValue, onError) => if (res.ok) { return res.json() } else { - onError?.() return initialValue } }) .then(newValue => { + onValue?.(newValue) setValue(newValue) }) diff --git a/client/pages/Problem.tsx b/client/pages/Problem.tsx index bb1c3a0..fbd7996 100644 --- a/client/pages/Problem.tsx +++ b/client/pages/Problem.tsx @@ -1,6 +1,6 @@ import { route } from 'preact-router' import { useContext, useState } from 'preact/hooks' -import { isAdministrator, Solution as SolutionModel } from '../../shared/model' +import { isAdministrator, Problem as ProblemModel, Solution as SolutionModel } from '../../shared/model' import { prependBaseUrl, server } from '../api' import { Header } from '../components/Header' import { MarkdownEditor } from '../components/MarkdownEditor' @@ -21,15 +21,13 @@ export const ProblemPage = ({ id }: RouteProps) => { const [source, setSource] = useState('') - const [{ content }] = useResource<{ content?: string }>( - `/api/problem/${id}`, - { - content: '', - }, - () => { + const [problem] = useResource(`/api/problem/${id}`, null, problem => { + if (problem === null) { route(prependBaseUrl('/')) } - ) + }) + + const content = problem?.content ?? '' const [solutions, refreshSolutions, setSolutionHeuristic] = useListResource( `/api/solutions?problem=${id}`