Build a movie search by year with validation, loading, empty and error states

mediumAbout 30 minutesUpdated CodingProAsked atChewyreactformsfetchvalidationabort-controllerrace-conditionsaccessibility
Not solved

Share this question

Problem

Build a small movie finder. The user types a year, clicks Search, and sees the titles of the movies released that year. In the interview the data came from GET https://jsonmock.hackerrank.com/api/moviesdata?Year={year}. Here the request is passed in as a prop, so the component can be tested without the network.

<MovieList fetchMovies />

fetchMovies(year, { signal }) takes the year as a number and returns a promise of the API's JSON:

{ page: 1, per_page: 10, total: 2, total_pages: 1,
  data: [{ Title: "Spectre", Year: 2015, imdbID: "tt2379713" }, { Title: "Inside Out", Year: 2015, imdbID: "tt2096673" }] }
  • A <form> holds a text input with the label Year (<label> linked to the input) and a submit button Search. The input starts empty. Typing does not search.
  • On submit, trim the value. It is valid when it is exactly four digits and does not start with 0 (so 2015 and 1999 are valid; abc, 201, 20155, 0999 and "" are not).
  • An invalid value does not call fetchMovies. It aborts any request in flight, clears the results and the status, shows <p role="alert">Enter a four-digit year, like 2015.</p>, and sets aria-invalid="true" on the input. The next valid submit removes the message and the attribute.
  • A valid value calls fetchMovies(Number(value), { signal }). While it runs, the previous list is removed.
  • A <p role="status"> is always rendered. It is empty at first and after an invalid submit, shows Loading… while a request runs, Found 2 movies from 2015 when there are results (Found 1 movie from 1999 for one), and No results found when data is empty.
  • Results render as <ul aria-label="Movies"> with one <li> per movie showing its Title, in the order the API returned them. Titles are rendered as text.
  • If the promise rejects, or the response has no data array, show <div role="alert"> containing Could not load movies. and a Retry button that searches the same year again.
  • A new search aborts the previous request, and a response that is not the latest is ignored. Unmounting aborts the request in flight.

Ref. UR-1537 · © UIRound · uiround.com/questions/build-a-movie-search-by-year-with-validation-loading-empty-and-error-states

Private, and saved in this browser as you type. All your notes are on My lists.

Every question and answer7 days, one payment