简体   繁体   中英

How do I get the search parameters to add to the url on submit, not on change?

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 parrameters, how can I remedy this?

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.

  1. Remove setSearchValue({ keyword: evt.target.value }) from input 's onChange handler.
  2. Add setSearchParams({ keyword: keywords }); to the form 's onSubmit handler.
  3. Reset/clear the search params in the 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>
  );
};

编辑 how-do-i-get-the-search-parameters-to-add-to-the-url-on-submit-not-on-change

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM