1
0
Fork 0
mirror of https://github.com/sussy-code/smov.git synced 2024-12-21 14:47:41 +01:00
smov/src/hooks/useSearchQuery.ts

42 lines
1,020 B
TypeScript
Raw Normal View History

2023-10-13 21:41:44 +02:00
import { useEffect, useState } from "react";
import { generatePath, useNavigate, useParams } from "react-router-dom";
function decode(query: string | null | undefined) {
return query ? decodeURIComponent(query) : "";
}
2022-05-03 20:58:34 +02:00
export function useSearchQuery(): [
2023-10-13 21:41:44 +02:00
string,
(inp: string, force?: boolean) => void,
() => void,
2022-05-03 20:58:34 +02:00
] {
const navigate = useNavigate();
2023-07-23 12:34:59 +02:00
const params = useParams<{ query: string }>();
const [search, setSearch] = useState(decode(params.query));
2023-10-13 21:41:44 +02:00
useEffect(() => {
setSearch(decode(params.query));
2023-10-13 21:41:44 +02:00
}, [params.query]);
const updateParams = (inp: string, commitToUrl = false) => {
setSearch(inp);
if (!commitToUrl) return;
if (inp.length === 0) {
navigate("/", { replace: true });
2023-07-23 12:34:59 +02:00
return;
}
navigate(
2023-07-23 12:34:59 +02:00
generatePath("/browse/:query", {
2023-10-13 21:41:44 +02:00
query: inp,
}),
{ replace: true },
);
};
const onUnFocus = (newSearch?: string) => {
2024-01-30 20:39:40 +01:00
updateParams(newSearch ?? search, true);
2022-05-03 20:58:34 +02:00
};
return [search, updateParams, onUnFocus];
}