Skip to content

Commit

Permalink
fix(frontend): encode special characters in search input to prevent c…
Browse files Browse the repository at this point in the history
…rashing router

re #252
  • Loading branch information
sct committed Dec 14, 2020
1 parent 8cb05c4 commit 15013d6
Showing 1 changed file with 15 additions and 4 deletions.
19 changes: 15 additions & 4 deletions src/hooks/useSearchInput.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@ import type { Nullable } from '../utils/typeHelpers';

type Url = string | UrlObject;

const encodeURIExtraParams = (string: string): string => {
return encodeURIComponent(string).replace(/!/g, '%21');
};

interface SearchObject {
searchValue: string;
searchOpen: boolean;
Expand Down Expand Up @@ -35,14 +39,17 @@ const useSearchInput = (): SearchObject => {
if (router.pathname.startsWith('/search')) {
router.replace({
pathname: router.pathname,
query: { ...router.query, query: debouncedValue },
query: {
...router.query,
query: encodeURIExtraParams(debouncedValue),
},
});
} else {
setLastRoute(router.asPath);
router
.push({
pathname: '/search',
query: { query: debouncedValue },
query: { query: encodeURIExtraParams(debouncedValue) },
})
.then(() => window.scrollTo(0, 0));
}
Expand Down Expand Up @@ -85,8 +92,12 @@ const useSearchInput = (): SearchObject => {
* is on /search
*/
useEffect(() => {
if (router.query.query !== debouncedValue) {
setSearchValue((router.query.query as string) ?? '');
if (router.query.query !== encodeURIExtraParams(debouncedValue)) {
setSearchValue(
router.query.query
? decodeURIComponent(router.query.query as string)
: ''
);

if (!router.pathname.startsWith('/search') && !router.query.query) {
setIsOpen(false);
Expand Down

0 comments on commit 15013d6

Please sign in to comment.