Vanilla Javascript Fetch Refresher
Terry Threatt
Posted on February 28, 2021
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
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))
}
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)
})
Now we should have all ten of our jokes rendering in a list
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
Posted on February 28, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
September 19, 2024