Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Async await and fetch syntax not working in React

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'
            }
        ]
    }
}
like image 210
jayscript Avatar asked Oct 20 '25 15:10

jayscript


1 Answers

As many people have said already, an async function will always return a Promise object, whose value you can then obtain by using .then().

In general, if you need to make many requests to a server, you should be using a state management framework such as Redux. However, Redux introduces a lot of boilerplate. If your usecase is simple, you could just use local UI state to store the result of your call.

Something like this:

export class App extends Component {
    constructor(props) {
      super(props)
      this.state = { sport: '' }
    }

    componentDidMount() {
      this.fetchSport('soccer').then(sport => this.setState({ sport }))
    }

    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.state.sport}
                />
            </div>
        )
    }
}
like image 172
Pedro Castilho Avatar answered Oct 23 '25 05:10

Pedro Castilho



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!