Modernize your ReactJS application with async/await in 2018
Kevin Le
Posted on December 31, 2017
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.
Posted on December 31, 2017
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.