2022-02-27 20:07:15 +01:00
|
|
|
import { MWMediaType, MWQuery } from "providers";
|
|
|
|
import React, { useState } from "react";
|
|
|
|
import { generatePath, useHistory, useRouteMatch } from "react-router-dom";
|
|
|
|
|
|
|
|
export function useSearchQuery(): [MWQuery, (inp: Partial<MWQuery>) => void] {
|
2022-02-28 22:00:32 +01:00
|
|
|
const history = useHistory();
|
|
|
|
const { path, params } = useRouteMatch<{ type: string; query: string }>();
|
2022-02-27 20:07:15 +01:00
|
|
|
const [search, setSearch] = useState<MWQuery>({
|
|
|
|
searchQuery: "",
|
|
|
|
type: MWMediaType.MOVIE,
|
|
|
|
});
|
|
|
|
|
|
|
|
const updateParams = (inp: Partial<MWQuery>) => {
|
2022-02-28 22:00:32 +01:00
|
|
|
const copySearch: MWQuery = { ...search };
|
2022-02-27 20:07:15 +01:00
|
|
|
Object.assign(copySearch, inp);
|
2022-05-01 23:32:33 +02:00
|
|
|
setSearch(copySearch);
|
2022-02-28 22:00:32 +01:00
|
|
|
history.replace(
|
|
|
|
generatePath(path, {
|
|
|
|
query:
|
|
|
|
copySearch.searchQuery.length === 0 ? undefined : inp.searchQuery,
|
|
|
|
type: copySearch.type,
|
|
|
|
})
|
|
|
|
);
|
|
|
|
};
|
2022-02-27 20:07:15 +01:00
|
|
|
|
|
|
|
React.useEffect(() => {
|
2022-02-28 22:00:32 +01:00
|
|
|
const type =
|
|
|
|
Object.values(MWMediaType).find((v) => params.type === v) ||
|
|
|
|
MWMediaType.MOVIE;
|
2022-02-27 20:07:15 +01:00
|
|
|
const searchQuery = params.query || "";
|
|
|
|
setSearch({ type, searchQuery });
|
2022-02-28 22:00:32 +01:00
|
|
|
}, [params, setSearch]);
|
2022-02-27 20:07:15 +01:00
|
|
|
|
2022-02-28 22:00:32 +01:00
|
|
|
return [search, updateParams];
|
2022-02-27 20:07:15 +01:00
|
|
|
}
|