Sampling method not defined with ES6 fetch in React

Hi guys, I have problems with fetch functions in my first js responsive application.

This is the structure of my project:

hello-world -- app -- components -- main.jsx -- node_modules -- public -- build.js -- index.html -- package.json 

This is what I installed using npm:

 npm install react react-dom babel-core babel-loader babel-preset-es2015 babel-preset-react webpack --save-dev npm install --save isomorphic-fetch es6-promise 

I am using webpack webpack.config

 module.exports = { entry: './app/components/main.jsx', output: { path: './public/', filename: "build.js", }, module: { loaders: [ { exclude: /(node_modules|bower_components)/, loader: 'babel', query: { presets: ['es2015', 'react'] } } ] } }; 

package.json

 { "name": "hello-world", "version": "1.0.0", "description": "", "main": "webpack.config.js", "scripts": { "build": "webpack -w" }, "author": "mannuk", "license": "MIT", "devDependencies": { "babel-core": "^6.14.0", "babel-loader": "^6.2.5", "babel-preset-es2015": "^6.14.0", "babel-preset-react": "^6.11.1", "react": "^0.14.8", "react-dom": "^0.14.8", "webpack": "^1.13.2" }, "dependencies": { "es6-promise": "^3.3.1", "isomorphic-fetch": "^2.2.1" } } 

This is the file in which I create the user interface:

main.jsx

 import React from 'react'; import ReactDOM from 'react-dom'; import 'isomorphic-fetch'; import 'es6-promise'; class Person extends React.Component { constructor(props){ super(props); this.state = {people : []}; } componentWillMount(){ fetch('xxx/people', method: 'get', headers: {'token' : 'xxx'} ) .then((response) => { return response.json() }) .then((people) => { this.setState({ people: people }) }) } render(){ return <div> <input type="text" value={this.state.people[0].name}></input> </div> } } ReactDOM.render( <Person/>, document.getElementById('container') ); 

If I try to run it through a browser, this will not work (the selection method is not defined). I also checked this released ES6 message `fetch is undefined` and I turned on the import without success. I also included the es6-prom import, but it doesn't work either.

What am I doing wrong? Is this a configuration problem or what? When I run "npm run build", there are no errors, and build.js looks fine.

+6
source share
2 answers

This is the exported default, so ...

 import fetch from 'isomorphic-fetch' 
+17
source

Adding polyfill for this is the right approach. When considering one of my recent projects, you just need to do the next import;

 import promise from 'es6-promise'; import 'isomorphic-fetch'; promise.polyfill(); 

It looks like you did not get the correct es6-prom import, which requires a call to the .polyfill () method. I would recommend placing them at the entry point of the application, since you will only need to import them once.

I would also recommend including babel polyfill;

 import 'babel-polyfill'; 
+2
source

All Articles