Modernize your ReactJS application with async/await in 2018

To start 2018, you can modernize your ReactJS application by incorporating the async/await feature. Assume you already use a Promise-based HTTP client library such as axios
, you can easily refactor your existing code, or you can just start using async/await in new codes.

Either way or both, here’s a small snippet that can help:

import axios from 'axios';
...
class Login extends Component {
    constructor(props, context) {
        super(props, context);
        this.onLogin = this.onLogin.bind(this);
        ...
    }
    async onLogin() {
        const { email, password } = this.state;
        try {
            const response = await axios.post('/login', { email, password });
            console.log(response);
        } catch (err) {
            //handle error
        }
    }
    ...
}

So the code change is very minimal. But running webpack
might result in an error. The error might say something like regeneratorRuntime is not defined
. In that case, it’s a simple fix:

npm install babel-plugin-transform-runtime --save-dev

Then in the .babelrc file, simply add

{
    ...
    "plugins": [
        ["transform-runtime", {
            "regenerator": true
        }]
    ]
}

Other than adding babel-plugin-transform-runtime
and a simple modification to the .babelrc file, no babel-runtime
, no polyfill
is necessary.

The Practical Developer稿源:The Practical Developer (源链) | 关于 | 阅读提示

本站遵循[CC BY-NC-SA 4.0]。如您有版权、意见投诉等问题,请通过eMail联系我们处理。
酷辣虫 » 综合技术 » Modernize your ReactJS application with async/await in 2018

喜欢 (0)or分享给?

专业 x 专注 x 聚合 x 分享 CC BY-NC-SA 4.0

使用声明 | 英豪名录