Fetch: Add Support for `import fetch from 'whatwg-fetch';`

Created on 30 Jun 2016  路  2Comments  路  Source: github/fetch

Most helpful comment

It might be a little cumbersome but something like this could work:

Make a little fetch utility module, that wraps up the whatwg-fetch.

// utils/fetch.js

// For browsers without Promise support
require('es6-promise').polyfill()
import 'whatwg-fetch'

// Can remove this if you would like
function checkStatus (response) {
  console.log('response.status', response.status)
  if (response.status >= 200 && response.status < 300) {
    return response
  }

  const error = new Error(response.statusText)
  error.response = response
  throw error
}

export default function whatwgFetch (url, options) {
  return fetch(url, options)
    .then(checkStatus)
}

Import your fetch utility to use in your module

// myModule.js
import whatwgFetch from '../utils/fetch'

whatwgFetch('/users.html')
  .then(function(response) {
    return response.text()
  }).then(function(body) {
    document.body.innerHTML = body
  })

All 2 comments

It's a polyfill, so you should never need to import it with a name, just like you never need to do import Promise from 'es6-promise'.

But if you insist, it should be doable currently

import * as fetch from 'whatwg-fetch';
import {fetch} from 'whatwg-fetch';

It might be a little cumbersome but something like this could work:

Make a little fetch utility module, that wraps up the whatwg-fetch.

// utils/fetch.js

// For browsers without Promise support
require('es6-promise').polyfill()
import 'whatwg-fetch'

// Can remove this if you would like
function checkStatus (response) {
  console.log('response.status', response.status)
  if (response.status >= 200 && response.status < 300) {
    return response
  }

  const error = new Error(response.statusText)
  error.response = response
  throw error
}

export default function whatwgFetch (url, options) {
  return fetch(url, options)
    .then(checkStatus)
}

Import your fetch utility to use in your module

// myModule.js
import whatwgFetch from '../utils/fetch'

whatwgFetch('/users.html')
  .then(function(response) {
    return response.text()
  }).then(function(body) {
    document.body.innerHTML = body
  })
Was this page helpful?
0 / 5 - 0 ratings

Related issues

huanghaiyang picture huanghaiyang  路  3Comments

hannesvdvreken picture hannesvdvreken  路  4Comments

shirotech picture shirotech  路  3Comments

ccorcos picture ccorcos  路  3Comments

poppinlp picture poppinlp  路  4Comments