DEV Community

Terry Threatt
Terry Threatt

Posted on

Vanilla Javascript Fetch Refresher

If you've been developing with any of the powerful Javascript frameworks/libraries like React, Vue, and Angular. Then like me, you can get a bit rusty with some pure DOM (Document Object Model) manipulation because these technologies will abstract lots of the heavy lifting. Here's a quick refresher to get you right back into the swing of things by fetching some hilarious programming jokes.

Let's get going with CodePen for brevity
Starter CodePen

First, let's make a new API request for jokes

const url = 'https://official-joke-api.appspot.com/jokes/programming/ten'

fetch(url)
  .then(response => response.json())
  .then(jokesObj => console.log(jokesObj)) // this shows an object of our jokes
Enter fullscreen mode Exit fullscreen mode

Next, let's create a helper function to see our jokes

fetch(url)
  .then(response => response.json())
  .then(jokesObj => renderJokes(jokesObj))

function renderJokes(jokes) { 
  jokes.forEach(joke => console.log(joke)) 
}
Enter fullscreen mode Exit fullscreen mode

Last, let's use our helper function to manipulate the DOM to render our jokes

function renderJokes(jokes) { 
  const jokesDiv = document.getElementById("jokes")
  jokes.forEach(joke => {
    const li = document.createElement('li')
    li.innerHTML = `
      ${joke.setup}
      </br>
      ${joke.punchline}
    `
    jokesDiv.appendChild(li)
  })
Enter fullscreen mode Exit fullscreen mode

Now we should have all ten of our jokes rendering in a list

Final

Final CodePen

Let's chat about Vanilla JS
Hopefully, this was a good and quick refresher on Vanilla Javascript DOM manipulation. If you enjoyed this post feel free to leave a comment about your thoughts and experiences working with Vanilla JS.

Happy Coding,
Terry Threatt

Top comments (0)