Build a movie search by year with validation, loading, empty and error states
mediumAbout 30 minutesUpdated CodingProAsked atChewyreactformsfetchvalidationabort-controllerrace-conditionsaccessibility
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(so2015and1999are valid;abc,201,20155,0999and""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 setsaria-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, showsLoading…while a request runs,Found 2 movies from 2015when there are results (Found 1 movie from 1999for one), andNo results foundwhendatais empty. - Results render as
<ul aria-label="Movies">with one<li>per movie showing itsTitle, in the order the API returned them. Titles are rendered as text. - If the promise rejects, or the response has no
dataarray, show<div role="alert">containingCould 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
Unlock this question
Its tests and the tested solution are part of Pro.
- 2
- code listings
- 8
- edge cases
- 5
- follow-up questions
What's inside
- Tests that check your solution
- Step-by-step
- Approach
- Solution
- Complexity
- Edge cases
- Follow-up questions
- Card worldwide
- UPI and net banking in India
- One-time payment, nothing renews
Private, and saved in this browser as you type. All your notes are on My lists.