From 0513ff558569ac51b6a5d0a366da001ff852e455 Mon Sep 17 00:00:00 2001 From: tymur999 Date: Sat, 11 Apr 2026 14:37:31 -0500 Subject: [PATCH] query param reader --- src/articles/ArticleContext.tsx | 34 ++++++++++++++++++++++++++++---- src/articles/mdx/high-school.mdx | 2 +- src/router/Route.tsx | 4 +++- 3 files changed, 34 insertions(+), 6 deletions(-) diff --git a/src/articles/ArticleContext.tsx b/src/articles/ArticleContext.tsx index b08cde9..b3e6ec7 100644 --- a/src/articles/ArticleContext.tsx +++ b/src/articles/ArticleContext.tsx @@ -1,6 +1,8 @@ -import {createContext, PropsWithChildren, useContext, useState} from "react"; +import {createContext, PropsWithChildren, useContext, useEffect, useState} from "react"; import {Reader} from "./Reader"; -import {Article} from "./articles"; +import {Article, ARTICLES} from "./articles"; +import {useRouter} from "../router/RouterContext"; +import {Path} from "../router/router"; const articleContext = createContext>>([undefined, function(){}]); @@ -9,9 +11,33 @@ export function useArticle() { return useContext(articleContext); } +const ARTICLE_QUERY = "a"; export default function ArticleProvider({ children }: PropsWithChildren) { - const state = useState
(undefined); - return + const [article, setArticle] = useState
(undefined); + const router = useRouter(); + + useEffect(() => { + const params = new URLSearchParams(location.search); + if(params.has(ARTICLE_QUERY)) { + const id = Number.parseInt(params.get(ARTICLE_QUERY)!); + setArticle(ARTICLES[id]); + } + }, [setArticle]); + + useEffect(() => { + if(!article) { + // query param + const params = new URLSearchParams(location.search); + if(params.has(ARTICLE_QUERY)) { + router.replacePage(location.pathname as Path); + } + } else { + const id = ARTICLES.indexOf(article); + router.replacePage(`${location.pathname}?${ARTICLE_QUERY}=${id}` as Path); + } + }, [article]); + + return {children} ; diff --git a/src/articles/mdx/high-school.mdx b/src/articles/mdx/high-school.mdx index 219108f..cef5114 100644 --- a/src/articles/mdx/high-school.mdx +++ b/src/articles/mdx/high-school.mdx @@ -6,7 +6,7 @@ import {ReactComponent as K8s} from "../../img/Kubernetes Logo Vector.svg"; # My high school experience -turtleneck thumbnail +turtleneck thumbnail My first coding experience was in middle school playing Code Combat. You could say Python is the first language I learned, not particularly uncommon. diff --git a/src/router/Route.tsx b/src/router/Route.tsx index b8975ef..4359136 100644 --- a/src/router/Route.tsx +++ b/src/router/Route.tsx @@ -13,8 +13,10 @@ export const ROUTES: Routes = [ function Route(props: PropsWithChildren & {route: Route}) { const {route: [path], children} = props; const router = useRouter(); + // remove search params + const [cleanPath] = /\/?\w*[^?]/.exec(router.current) ?? [path]; - return <>{router.current === path && children} + return <>{cleanPath === path && children} }