mirror of
https://github.com/sussy-code/smov.git
synced 2024-12-21 14:47:41 +01:00
41 lines
1,020 B
TypeScript
41 lines
1,020 B
TypeScript
import { useEffect, useState } from "react";
|
|
import { generatePath, useNavigate, useParams } from "react-router-dom";
|
|
|
|
function decode(query: string | null | undefined) {
|
|
return query ? decodeURIComponent(query) : "";
|
|
}
|
|
|
|
export function useSearchQuery(): [
|
|
string,
|
|
(inp: string, force?: boolean) => void,
|
|
() => void,
|
|
] {
|
|
const navigate = useNavigate();
|
|
const params = useParams<{ query: string }>();
|
|
const [search, setSearch] = useState(decode(params.query));
|
|
|
|
useEffect(() => {
|
|
setSearch(decode(params.query));
|
|
}, [params.query]);
|
|
|
|
const updateParams = (inp: string, commitToUrl = false) => {
|
|
setSearch(inp);
|
|
if (!commitToUrl) return;
|
|
if (inp.length === 0) {
|
|
navigate("/", { replace: true });
|
|
return;
|
|
}
|
|
navigate(
|
|
generatePath("/browse/:query", {
|
|
query: inp,
|
|
}),
|
|
{ replace: true },
|
|
);
|
|
};
|
|
|
|
const onUnFocus = (newSearch?: string) => {
|
|
updateParams(newSearch ?? search, true);
|
|
};
|
|
|
|
return [search, updateParams, onUnFocus];
|
|
}
|