Here is my code:
export class App extends Component {
constructor(props) {
super(props)
}
async fetchSport(sport) {
let headers = new Headers()
headers.append('key-goes-here', 'pass-goes-here')
headers.append('Accept', 'application/json')
let request = new Request('api-url-goes-here' + sport, {headers: headers})
let data = await fetch(request).then(response => response.json()).then(json => json.players.forward)
console.log(data) // 'Christopher Brown'
return data
}
render() {
return (
<div className='app'>
<SportPlayers
sport={this.fetchSport('soccer')}
/>
</div>
)
}
}
Uncaught Error: Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead or wrap the object using createFragment(object) from the React add-ons. Check the render method of `SportPlayers`.
I am trying to figure out why this error is showing. The fetchSport function should be returning a string (like console.log suggests), but it seems like a promise is returned to the view instead.
Bellow is my webpack.config.js:
var webpack = require("webpack");
module.exports = {
entry: ["babel-polyfill", "./src/index.js"],
output: {
path: "/dist/assets",
filename: "bundle.js",
publicPath: "assets"
},
devServer: {
inline: true,
contentBase: "./dist",
port: 3000
},
module: {
loaders: [
{
test: /\.js$/,
exclude: /(node_modules)/,
loader: ["babel-loader", 'babel-loader?presets[]=es2016,presets[]=stage-3,presets[]=react'],
},
{
test: /\.json$/,
exclude: /(node_modules)/,
loader: ["json-loader"]
},
{
test: /\.css$/,
loader: 'style-loader!css-loader!autoprefixer-loader'
},
{
test: /\.scss$/,
loader: 'style-loader!css-loader!autoprefixer-loader!sass-loader'
}
]
}
}
fetchmethod fromrender. Also,fetchSportreturns a promise, which you cannot pass toSportPlayersasynchronouscode the same way you would write synchronous code. Maybe you should start by learning how es6 generators works to fully understand the concept of async awaitthis.fetchSport('soccer').then(data => console.log(data))fetchin this case? What is the correct context to invoke it. I am new to React.