Skip to content

Commit

Permalink
Fix #1630 - triggering search via URL
Browse files Browse the repository at this point in the history
  • Loading branch information
DukeManh committed Feb 14, 2021
1 parent 128eb7a commit b6c376a
Showing 1 changed file with 10 additions and 9 deletions.
19 changes: 10 additions & 9 deletions src/frontend/next/src/components/SearchPage.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { FormEvent, useState } from 'react';
import { FormEvent, useState, useEffect } from 'react';
import { makeStyles } from '@material-ui/core/styles';
import { useRouter } from 'next/router';

Expand All @@ -23,12 +23,10 @@ const SearchPage = () => {
// We synchronize the `text` and `filter` values to the URL's query string
// Router query object for a query can be an array if url becomes text=123&text=456
// https://stackoverflow.com/questions/60110364/type-string-string-is-not-assignable-to-type-string
const [textParam = '', setTextParam] = useState(
Array.isArray(router.query.text) ? router.query.text[0] : router.query.text
);
const [filterParam = 'post', setFilterParam] = useState<FilterProp['filter']>(
router.query.filter === 'post' ? 'post' : 'author'
);
const textParam = Array.isArray(router.query.text)
? router.query.text[0]
: router.query.text || '';
const filterParam = router.query.filter === 'post' || !router.query.filter ? 'post' : 'author';

// We manage the state of `text` and `filter` internally, and update URL on
// form submit only. These are used in the <SearchBar>, and the user can change them.
Expand All @@ -38,11 +36,14 @@ const SearchPage = () => {
// Form was submitted, so go ahead and sync to URL, (re)triggering search.
function onSubmitHandler(event: FormEvent) {
event.preventDefault();
setTextParam(text);
setFilterParam(filter);
router.push(`/search?text=${text}&filter=${filter}`);
}

useEffect(() => {
setText(textParam);
setFilter(filterParam);
}, [textParam, filterParam]);

return (
<div>
<div className={classes.anchor} id="back-to-top-anchor" />
Expand Down

0 comments on commit b6c376a

Please sign in to comment.