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-02-27 20:07:15 +01:00
|
|
|
|
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
|
|
|
|
] {
|
2022-02-28 22:00:32 +01:00
|
|
|
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 ?? "");
|
2022-02-27 20:07:15 +01:00
|
|
|
|
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;
|
|
|
|
}
|
2022-02-28 22:00:32 +01:00
|
|
|
history.replace(
|
2023-07-23 12:34:59 +02:00
|
|
|
generatePath("/browse/:query", {
|
2023-10-13 21:41:44 +02:00
|
|
|
query: inp,
|
2022-02-28 22:00:32 +01:00
|
|
|
})
|
|
|
|
);
|
|
|
|
};
|
2022-02-27 20:07:15 +01:00
|
|
|
|
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];
|
2022-02-27 20:07:15 +01:00
|
|
|
}
|