movie-web/src/hooks/useSearchQuery.ts

56 lines
1.6 KiB
TypeScript
Raw Normal View History

2022-05-03 20:58:34 +02:00
import React, { useRef, useState } from "react";
import { generatePath, useHistory, useRouteMatch } from "react-router-dom";
2022-12-13 23:50:13 +01:00
import { MWMediaType, MWQuery } from "@/providers";
2022-05-03 20:58:34 +02:00
export function useSearchQuery(): [
MWQuery,
(inp: Partial<MWQuery>, force: boolean) => void,
() => void
] {
const history = useHistory();
2022-05-03 21:06:27 +02:00
const isFirstRender = useRef(true);
const { path, params } = useRouteMatch<{ type: string; query: string }>();
const [search, setSearch] = useState<MWQuery>({
searchQuery: "",
type: MWMediaType.MOVIE,
});
2022-05-03 20:58:34 +02:00
const updateParams = (inp: Partial<MWQuery>, force: boolean) => {
const copySearch: MWQuery = { ...search };
Object.assign(copySearch, inp);
setSearch(copySearch);
2022-05-03 20:58:34 +02:00
if (!force) return;
history.replace(
generatePath(path, {
query:
copySearch.searchQuery.length === 0 ? undefined : inp.searchQuery,
type: copySearch.type,
})
);
};
2022-05-03 20:58:34 +02:00
const onUnFocus = () => {
history.replace(
generatePath(path, {
query: search.searchQuery.length === 0 ? undefined : search.searchQuery,
type: search.type,
})
);
};
// only run on first load of the page
React.useEffect(() => {
2022-05-03 21:06:27 +02:00
if (isFirstRender.current === false) {
2022-05-03 20:58:34 +02:00
return;
}
2022-05-03 21:06:27 +02:00
isFirstRender.current = false;
const type =
Object.values(MWMediaType).find((v) => params.type === v) ||
MWMediaType.MOVIE;
const searchQuery = params.query || "";
setSearch({ type, searchQuery });
2022-05-03 20:58:34 +02:00
}, [setSearch, params, isFirstRender]);
2022-05-03 20:58:34 +02:00
return [search, updateParams, onUnFocus];
}