mirror of
https://github.com/movie-web/movie-web.git
synced 2024-11-10 21:45:06 +01:00
fix debounce on first render
This commit is contained in:
parent
d161c948cd
commit
8e522e18d4
@ -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];
|
||||
}
|
||||
|
@ -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;
|
||||
|
Loading…
Reference in New Issue
Block a user