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

37 lines
846 B
TypeScript
Raw Normal View History

2023-10-13 21:41:44 +02:00
import { useEffect, useState } from "react";
2023-07-23 12:34:59 +02:00
import { generatePath, useHistory, useParams } from "react-router-dom";
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,
2022-05-03 20:58:34 +02:00
() => void
] {
const history = useHistory();
2023-07-23 12:34:59 +02:00
const params = useParams<{ query: string }>();
2023-10-13 21:41:44 +02:00
const [search, setSearch] = useState(params.query ?? "");
2023-10-13 21:41:44 +02:00
useEffect(() => {
setSearch(params.query ?? "");
}, [params.query]);
const updateParams = (inp: string, commitToUrl = false) => {
setSearch(inp);
if (!commitToUrl) return;
if (inp.length === 0) {
2023-07-23 12:34:59 +02:00
history.replace("/");
return;
}
history.replace(
2023-07-23 12:34:59 +02:00
generatePath("/browse/:query", {
2023-10-13 21:41:44 +02:00
query: inp,
})
);
};
2022-05-03 20:58:34 +02:00
const onUnFocus = () => {
2023-10-13 21:41:44 +02:00
updateParams(search, true);
2022-05-03 20:58:34 +02:00
};
return [search, updateParams, onUnFocus];
}