fix debounce on first render

This commit is contained in:
Jelle van Snik 2023-01-14 16:14:54 +01:00
parent d161c948cd
commit 8e522e18d4
2 changed files with 10 additions and 20 deletions

View File

@ -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<MWQuery>, force: boolean) => void,
() => void
] {
const history = useHistory();
const isFirstRender = useRef(true);
const { path, params } = useRouteMatch<{ type: string; query: string }>();
const [search, setSearch] = useState<MWQuery>({
searchQuery: "",
type: MWMediaType.MOVIE,
});
const [search, setSearch] = useState<MWQuery>(getInitialValue(params));
const updateParams = (inp: Partial<MWQuery>, 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];
}

View File

@ -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;