Search code examples
javascriptapireddit

Is there a way to check if a subreddit search doesnt contain anything using reddits API using JS


I am trying to check if a a subreddit contains ANY posts that match the users search criteria. Ive tried a few methods but non of them seem to be able to only rely if the results are empty or not.

fetch(`https://www.reddit.com/r/${redsearch}/search.json?q=${redsearch}&restrict_sr=on&sort=relevance&t=all&limit=100`)
    .then(function (response) {
        return response.json()
    }

this is currently what i found to be the only thing that comes close to searching and returning the results but I am unable to understand how I can filter out the JSON so I can check weather the search was successful or if the search result was empty

can help or ideas will be greatly appreciated


Solution

  • It looks to me like the response object has a data property and inside that a children property. If the children property is empty that would mean no results found for that search. You can compare these two responses that I got.

    {
      "kind": "Listing",
      "data": {
        "modhash": "",
        "dist": 0,
        "facets": {},
        "after": null,
        "geo_filter": "",
        "children": [],
        "before": null
      }
    }
    

    and

    {
      "kind": "Listing",
      "data": {
        "modhash": "",
        "dist": 1,
        "facets": {},
        "after": "t3_vwcqap",
        "geo_filter": "",
        "children": [
          {
            /*removed data to make it clearer*/
          }
        ],
        "before": null
      }
    }