somascope
10/11/2018 - 6:12 PM

Fetch and JSON example

// Example 1
const endpoint = 'https://gist.githubusercontent.com/Miserlou/c5cd8364bf9b2420bb29/raw/2bf258763cdddd704f8ffd3ea9a3e81d25e2c6f6/cities.json';
const cities = [];

fetch(endpoint)
  .then(response => response.json())
  .then(data => cities.push(...data))

// Example 2
const getPosts = () => {
  fetch(`http://jsonplaceholder.typicode.com/posts`)
    .then(response => response.json())
    .then(posts => console.log(posts))
}

// Be sure to add error handling via .catch() !!

// Notes
// 1. fetch(endpoint) // Call fetch with your API/endpoint URL

// 2.   .then(res => res.json()) // fetch returns a promise, which you can use 'res' as the response
                                 // You must use the Response json() method to return another promise
                                 
// 3.   .then(data => cities.push(...data)) // Finally, you can access the data
                                            // To set this in a const array, you must
                                            // use the spread operator: ...variable

// Example 3: Using POST
// a. Create a new post
const post = {
  title: 'My FETCHING fetch',
  body: 'Go get it, doggie!',
  userId: 1
}

// b. Function to post the post
const newPost = post => {
  const options = {
    method: 'POST',
    body: JSON.stringify(post),
    headers: new Headers({
      'Content-Type': 'application/json'
    })
  }
  return fetch(`http://jsonplaceholder.typicode.com/posts`, options)
    .then(res => res.json())
    .then(res => console.log(res))
    .catch(error => console.error(`Error: ${error}`))
}
newPost(post)