Reputation: 11
The URL format is as follows:
www.url.com/keyword="_____"
However, the ____ portion of the url starts to fill in even before I submit the form? It works on submit as well but I've noticed in my console that every letter is being logged.
I infer that is because my input is set to onChange instead of onSubmit but after changing it onSubmit it doesn't work anymore.
The keyword also sticks around after refreshing the page instead of going back to the original base URL sans parameters, how can I remedy this?
Upvotes: 1
Views: 607
Reputation: 202658
The reason the URL queryString updates as soon as you are typing in the input is because you are updating the search params in the input's onChange
handler.
If you want to only update the queryString when the form is submitting then this is the handler to use to update the queryString params.
setSearchValue({ keyword: evt.target.value })
from input
's onChange
handler.setSearchParams({ keyword: keywords });
to the form
's onSubmit
handler.useEffect
when the component mounts.Code:
const SearchBox = ({
onSubmit: onSubmitCallback,
searchBoxLabel,
searchBoxPlaceholder,
searchBoxButtonText,
searchBoxHeader,
searchBoxDescription,
listingType
}) => {
const dispatch = useDispatch();
const keywords = useSelector((state) => state.searchReducer.Keywords);
const [searchParams, setSearchParams] = useSearchParams();
useEffect(() => {
setSearchParams(); // <-- clear the search params on component mount
}, []);
const handleSubmit = (e) => {
e.preventDefault();
onSubmitCallback(keywords);
setSearchParams({ keyword: keywords }); // <-- set search params
dispatch(setFilters([]));
// clear all checkboxes
document
.querySelectorAll("input[type=checkbox]")
.forEach((el) => (el.checked = false));
};
return (
<div className={....}>
...
<form className="search-banner__form" onSubmit={handleSubmit}>
<div className="search-banner__keyword-input-group">
...
<input
...
onChange={(evt) => {
dispatch(setKeywords(evt.currentTarget.value)); // <-- only update keywords
}}
/>
</div>
<button ... type="submit">
{searchBoxButtonText}
</button>
</form>
</div>
);
};
Upvotes: 1