Search code examples
javascriptjsonapireddit

Fetch hi res images from reddit


I'm trying to fetch the hi res images from a subreddit by recency. I can pull the thumbnails but can't figure out how to pull the real hi res images.

Here's my code:

fetch('https://www.reddit.com/r/cats.json')
  .then(res => res.json())
  .then(res => res.data.children)
  .then(res => res.map(post => ({
    author: post.data.author,
    link: post.data.url,
    img: post.data.thumbnail,
    title: post.data.title
  })))
  .then(res => res.map(render))
  .then(res => console.log(res))

const app = document.querySelector('#app');

const render = post => {
  const node = document.createElement('div');
  node.innerHTML = `
      <a href="${post.link}">
        <img src="${post.img}"/>
      </a>`;
  app.appendChild(node);
}

& here's my fiddle

Any ideas?


Solution

  • Looks like you need to swap around your href and img src

    fetch('https://www.reddit.com/r/cats.json')
    .then(res => res.json())
    .then(res => res.data.children)
    .then(res => res.map(post => ({
      author: post.data.author,
      link: post.data.url,
      img: post.data.thumbnail,
      title: post.data.title
    })))
    .then(res => res.map(render))
    .then(res => console.log(res))
    
    const app = document.querySelector('#app');
    const render = post => {
    const node = document.createElement('div');
     node.innerHTML = `
      <a href="${post.img}">
        <img src="${post.link}"/>
      </a>`;
    app.appendChild(node);
    }
    

    Fiddle: https://jsfiddle.net/qt7ktv4L/2/