seanmturley / natureddit

A simple Reddit client, featuring a landing page dedicated to nature with posts pulled from a curated list of subreddits.
0 stars 1 forks source link

Implement SearchDropdown API calls #128

Closed seanmturley closed 1 year ago

seanmturley commented 1 year ago

Description

The API call itself will be initiated in the SearchBar component. This has direct access to the trimmedSearchTerm and can conditionally render the SearchDropdown only when subreddit results exist.

The child components of SearchBar can access the fetched data directly with the associated useQuery hook, leveraging the fact that subsequent requests for the same data are automatically de-duped by RTK Query.

Tasks

seanmturley commented 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.

seanmturley commented 1 year ago

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.

seanmturley commented 1 year ago

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:

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.

seanmturley commented 1 year ago

After the refactor, I'm happy with this code.