React / handle error if user enters incorrect query format into search bar

I built a React app that fetches data from the New York Times Bestseller Books API and allows users to search for different lists by the publish date.

The NYTimes built this API so that dates must be entered in YYYY-MM-DD format for search queries. I added a placeholder in the search bar to inform the user of the correct format, but I want to know how I can handle the error if the user enters the date in the incorrect format (such as MM-DD-YYYY). Currently the app just crashes. To be clear, I’m thinking about user experience here - I want them to see a snackbar or alert that they’ve entered the date incorrectly, rather than having the app crash, requiring them to navigate back.

I should mention this is just a personal / student project for my portfolio. Here’s a link to the Github Repo.

Here is the code for my search bar:

src/pages/Home.jsx

  const [formData, setFormData] = React.useState({
     date: "",
  });


  const getBestsellersByDate = async (date) => {
    const response = await fetch(url + "/bestsellers/" + date, {
      method: "get",
      headers: {},
    });
    const fetchedBestsellers = await response.json();
    dispatch({ type: "getBestsellers", payload: fetchedBestsellers });
  };
const handleChange = (event) => {
    setFormData({ ...formData, [event.target.name]: event.target.value });
  };

  
const handleSubmit = (event) => {
    event.preventDefault();
    try {
      if(Date.parse(formData.date)) {
        // books index from search date
        getBestsellersByDate(formData.date);
        setFormData({
          date: "",
        });
      }
      } catch (error) {
      event.preventDefault();
       alert.error(
         <div>
           Please log in!
         </div>
       );
      console.log("enter valid date!");
    }
  };


        <div className="search-form_container">
          <Form inline onSubmit={handleSubmit}>
            <Form.Control
              type="text"
              name="date"
              pattern="/^\d{4}\-(0?[1-9]|1[012])\-(0?[1-9]|[12][0-9]|3[01])$/"
              className="search-form mr-sm-2"
              value={formData.date}
              onChange={handleChange}
              placeholder="YYYY-MM-DD"
            />
            <button id="btn-search" type="submit">
              Search
            </button>
          </Form>
        </div>

I think this is not what you want, but just in case it helps…

One thing you could do is disable the “Search” button, so they don’t submit the form. Then, you check dynamically for the onChange of the input. Once that value matches the format expected, you enable the button. But you still keep checking for onChange and once the input stops matching your format, you disable it again.

I am sure there are better ways, and I think this is not exactly what you wanted, but just in case this helps in the meantime.

Edit: By the way, the site is absolutely dope! :tada: