From 8e522e18d40d75029f370a598d8121884b204a9d Mon Sep 17 00:00:00 2001 From: Jelle van Snik Date: Sat, 14 Jan 2023 16:14:54 +0100 Subject: [PATCH] fix debounce on first render --- src/hooks/useSearchQuery.ts | 29 +++++++++----------------- src/views/search/SearchResultsView.tsx | 1 - 2 files changed, 10 insertions(+), 20 deletions(-) diff --git a/src/hooks/useSearchQuery.ts b/src/hooks/useSearchQuery.ts index b20c78ab..372c70fc 100644 --- a/src/hooks/useSearchQuery.ts +++ b/src/hooks/useSearchQuery.ts @@ -1,19 +1,23 @@ import { MWMediaType, MWQuery } from "@/backend/metadata/types"; -import React, { useRef, useState } from "react"; +import { useState } from "react"; import { generatePath, useHistory, useRouteMatch } from "react-router-dom"; +function getInitialValue(params: { type: string; query: string }) { + const type = + Object.values(MWMediaType).find((v) => params.type === v) || + MWMediaType.MOVIE; + const searchQuery = params.query || ""; + return { type, searchQuery }; +} + export function useSearchQuery(): [ MWQuery, (inp: Partial, force: boolean) => void, () => void ] { const history = useHistory(); - const isFirstRender = useRef(true); const { path, params } = useRouteMatch<{ type: string; query: string }>(); - const [search, setSearch] = useState({ - searchQuery: "", - type: MWMediaType.MOVIE, - }); + const [search, setSearch] = useState(getInitialValue(params)); const updateParams = (inp: Partial, force: boolean) => { const copySearch: MWQuery = { ...search }; @@ -38,18 +42,5 @@ export function useSearchQuery(): [ ); }; - // only run on first load of the page - React.useEffect(() => { - if (isFirstRender.current === false) { - return; - } - isFirstRender.current = false; - const type = - Object.values(MWMediaType).find((v) => params.type === v) || - MWMediaType.MOVIE; - const searchQuery = params.query || ""; - setSearch({ type, searchQuery }); - }, [setSearch, params, isFirstRender]); - return [search, updateParams, onUnFocus]; } diff --git a/src/views/search/SearchResultsView.tsx b/src/views/search/SearchResultsView.tsx index 20764b22..8638ec71 100644 --- a/src/views/search/SearchResultsView.tsx +++ b/src/views/search/SearchResultsView.tsx @@ -53,7 +53,6 @@ export function SearchResultsView({ searchQuery }: { searchQuery: MWQuery }) { useEffect(() => { // TODO use cache - // TODO run immediately without debounce on mount async function runSearch(query: MWQuery) { const searchResults = await runSearchQuery(query); if (!searchResults) return;