Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[issue 1630] Triggering search via URL #1657

Closed
wants to merge 6 commits into from
Closed
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