diff --git a/frontend/src/app/[locale]/look/QueryProvider.tsx b/frontend/src/app/[locale]/look/QueryProvider.tsx new file mode 100644 index 0000000000..1cbd5bfe33 --- /dev/null +++ b/frontend/src/app/[locale]/look/QueryProvider.tsx @@ -0,0 +1,35 @@ +"use client" + +import React, { use } from "react" +import { createContext, useCallback, useContext, useMemo, useState } from 'react'; +import { useSearchParams } from "next/navigation"; +import { set } from "lodash"; + +export const QueryContext = createContext({}); + +export default function QueryProvider({ + children, + }: { + children: React.ReactNode + }) { + const searchParams = useSearchParams() || undefined; + const defaultTerm = searchParams?.get('query'); + const [queryTerm, setQueryTerm] = useState(defaultTerm); + console.log("rendering provider:", queryTerm); + + const updateQueryTerm = useCallback((term: string) => { + setQueryTerm(term); + }, []); + + const contextValue = useMemo(() => ({ + queryTerm, + updateQueryTerm + }), [queryTerm, updateQueryTerm]); + + return ( + +

Query Provider

+ {children} +
+ ) +} \ No newline at end of file diff --git a/frontend/src/app/[locale]/look/SearchBar.tsx b/frontend/src/app/[locale]/look/SearchBar.tsx index e1c81461a6..39f6a4dfe3 100644 --- a/frontend/src/app/[locale]/look/SearchBar.tsx +++ b/frontend/src/app/[locale]/look/SearchBar.tsx @@ -3,32 +3,35 @@ import { Icon } from "@trussworks/react-uswds"; import { sendGAEvent } from "@next/third-parties/google"; import { useSearchParams, usePathname, useRouter } from 'next/navigation'; -import { useState } from "react"; +import { QueryContext } from "./QueryProvider"; +import { useContext, useState } from "react"; interface SearchBarProps { query: string; } export default function SearchBar({ query }: SearchBarProps) { - const[term, setTerm] = useState(null) + let { queryTerm, updateQueryTerm } = useContext(QueryContext); const searchParams = useSearchParams() || undefined; const pathname = usePathname() || ""; const router = useRouter(); + console.log("queryTerm:", queryTerm, "vs. query:", query); const handleSubmit = () => { const params = new URLSearchParams(searchParams); - if (term) { - params.set('query', term); + if (queryTerm) { + params.set('query', queryTerm); } else { params.delete('query'); } - sendGAEvent("event", "search", { search_term: term }); + sendGAEvent("event", "search", { search_term: queryTerm }); router.replace(`${pathname}?${params.toString()}`); }; return (
+

queryTerm: {queryTerm}