3d cartoon hands holding a phone

Unlock full course by purchasing a membership

Lesson 8

Using the Expand Operator to Fetch Recursively

The last addition to our stream

STANDARD

Using the Expand Operator to Fetch Recursively

The last key feature we need to implement is to actually make use of the gifsRequired value (i.e. how many gifs we should display per request), but there is some hidden complexity here. Let’s consider how we would actually implement this.

At the moment, we fetch GIFs from this URL:

  `https://www.reddit.com/r/${subreddit}/hot/.json?limit=100` +
    (after ? `&after=${after}` : '')

Notice that we supply a limit=100 to tell the Reddit API how many posts we want to return. It then might seem sensible to implement a gifsRequired limit like this:

  `https://www.reddit.com/r/${subreddit}/hot/.json?limit=${gifsRequired}` +
    (after ? `&after=${after}` : '')

However, that won’t quite work for us. At the moment this is what we do:

  1. Fetch 100 posts from Reddit
  2. Filter those to only include valid GIFs
  3. Display those GIFs

The actual number of GIFs we end up displaying in our application won’t necessarily be 100 or whatever limit we supply, it could be anywhere from 0 to 100. This is where things get tricky.

We will continue to discuss this as we implement the solution, but the general idea that we want to implement is (assuming an initial gifsRequired value of 20):

  1. Fetch 100 posts from Reddit
  2. Filter those for valid GIFs
  3. If there are more than 20 valid GIFs, trim them to just 20
  4. If there are less than 20 valid GIFs, keep hitting the API until we do have 20 valid GIFs

The tricky part is that last step, and it is where the expand operator will become extremely useful.

Implement the expand operator

STANDARD
Key

Thanks for checking out the preview of this lesson!

You do not have the appropriate membership to view the full lesson. If you would like full access to this module you can view membership options (or log in if you are already have an appropriate membership).