Navigating JSON tree to data from Reddit API

Viewed 253

I will try and keep this short. I am a current student and have been attempting to retrieve the top 5 posts from the front page of Reddit and display the title and URL on an HTML page. It is probably something really simple, but I can't get it to work. I want to pass the data to my Handlebars template from a single variable. I keep receiving an unhandled promise warning. Here is my code.

let url = 'https://www.reddit.com/.json?limit=5';
let settings = { method: "Get"};
let redditData = ""
fetch(url, settings)
    .then(res => res.json())
    .then(data => {
        redditData = [
    {
    title: data.children.data.title,
    url: data.children.data.url_overriden_by_dest
    }
    ];
});
3 Answers

The data object is structured differently than they way you've coded it. Here is how to extract the information you want from the first child:

let url = 'https://www.reddit.com/.json?limit=5';
let settings = { method: "Get"};
let redditData = ""
fetch(url, settings)
    .then(res => res.json())
    .then(data => {
        redditData = [
    {
    title: data.data.children[0].data.title,
    url: data.data.children[0].data.url_overriden_by_dest
    }
    ];
});

You might want to check some documentation on how the function fetch works here.

Also, check how promises work here.

That being said, you have to access the object properties, only when the Promise has finished retrieving the data. One way is using the Promise.allSettled function.

Please see the following snippet working, with a slightly different way of organizing it:

const url = "https://www.reddit.com/.json?limit=5";
const promise = fetch(url).then(res => res.json());

function formatHandlebarsData(data) {
  const childrenObj = data.value.data.children;
  
  return childrenObj.map(element => ({
    title: element.data.title,
    url: element.data.url
  }));
}

Promise.allSettled([promise]).then(([data]) => {
  const handlebarsData = formatHandlebarsData(data);
  
  // You can use the object now
  console.log(handlebarsData);
});

Awesome. I was able to get it working with

let url = 'https://www.reddit.com/.json?limit=5';
let settings = { method: "Get"};
let redditData = ""
fetch(url, settings)
    .then(res => res.json())
    .then(data => {
        redditData = [
    {
    title: data.data.children[0].data.title,
    url: data.data.children[0].data.url_overriden_by_dest
    }
    ];
});

Thanks!

Related