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

Time:07-23

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

CodePudding user response:

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
  }
}

CodePudding user response:

as @jaacima mentioned you can check it within the children property to see if any results were found

    fetch(`https://www.reddit.com/r/crackwatch/search.json?q=${redsearch}&restrict_sr=on&sort=relevance&t=all&limit=100`)
    .then(function (response) {
        return response.json()
    })
    .then(function (data) {
        if (data.data.children.length === 0) {
            console.log("No results found")
        }
        else
        {
            console.log("Results found")
        }
    })

heres the code snippet for anyone who stumbles across this problem

  • Related