Closed seanmturley closed 1 year ago
Set up API endpoint getSubreddits
.
Note that the API only returns real results for query strings of 3 or more characters. However, when the query is an empty string it returns this:
{
"kind": "Listing",
"data": {
"modhash": "2lmmdkm4rra7589ff221a80d6a1e96ef041c5d4adcaac9094f",
"dist": 0,
"facets": {},
"after": null,
"geo_filter": "",
"children": [],
"before": null
}
}
This causes trouble because it still contains a data.children
node, which is passed into the app via the useGetSubreddits
hook as data
. Because this data
is an empty array (i.e. a truthy value), the usual logical checks reliant on data
being falsy when no results are returned won't work.
To fix this a conditional check was added to the API endpoint's transformResponse
to make sure null
is returned when no real results are found.
This is working now.
Unfortunately the community_icon
for each subreddit isn't accessible (it returns a 403 error), so I've had to use the icon_img
value instead. It's not ideal, but still gives a reasonable icon for many subreddits. For those that don't have an icon_img
, I've added a fallback to a placeholder SVG icon.
At this point I think it's clear I should refactor SearchDropdownOptions
so that it only builds out a single option (it will be renamed in the singular). The mapping can occur in its parent, SearchDropdown
.
As mentioned in the previous comment, I've refactored so that mapping over the subreddits now occurs in SearchDropdown
, and SearchDropdownOption
(renamed in the singular) only handles single subreddits. The <li>
for each subreddit option is also being rendered in SearchDropdown
. The entire search-option
block is now rendered in SearchDropdown
.
These changes confer a number of advantages:
SearchDropdown
).SearchDropdownOption
can now receive data for a single subreddit via props, preventing the need for an additional useQuery
and simplifying data access.<li>
for each option carries all of the navigation logic, it's no longer necessary to pass focus
and setFocus
to SearchDropdownOption
via props.handleInputSubmit
and trimmedSearchTerm
via props for use in the search-option
block.The main disadvantage is that there is a small amount of awkward overlap in styling rules between SearchDropdown
and SearchDropdownOption
, but this is for the most part just a single rule that targets both .sr-option
and .search-option
.
After the refactor, I'm happy with this code.
Description
The API call itself will be initiated in the
SearchBar
component. This has direct access to thetrimmedSearchTerm
and can conditionally render theSearchDropdown
only when subreddit results exist.The child components of
SearchBar
can access the fetched data directly with the associateduseQuery
hook, leveraging the fact that subsequent requests for the same data are automatically de-duped by RTK Query.Tasks
SearchBar
SearchDropdown
SearchDropdownOptions