Using async / await with React

I’m currently toying with thunks vs Sagas.

The idea of re-writing a significant portion of my app’s API connectivity (from thunk, to saga) is not entirely thrilling. However, sagas do appear to be the better solution given what I currently know, and would choose them if starting again from scratch.

The gist of my problem is that thunks have added in a layer of complexity – but they work.

For any API call that should be authenticated, I need to catch the call using a middleware and then add the necessary token, and so on.

Combine this with Redux Form, however, and I am left with a bit of a head-scratcher. This middleware is generic. If certain calls fail, I need to map the response (containing error messages) to an object that Redux Form understands, then dispatch the stopSubmit action.

Anyway, enough about my problem.

Before making the switch I found a potential solution that involves using async / await. Being a sucker for new and shiny, I wanted to get it into my project.

Simply trying to use async / await resulted in an error for me:

Uncaught ReferenceError: regeneratorRuntime is not defined

Boo.

To fix this, I needed to import the babel-polyfill. However, a thing I found out is that you can import this dependency once in one of your top level components, rather than per file.

For example, in my project I have an App component which contains a container which all other components in the app render into.

I added the single line:

import "babel-polyfill";

as the first line in the file, and nowasync / await works just fine.

These other two files may help in setting up:

  "devDependencies": {
    "babel-cli": "6.14.0",
    "babel-core": "6.14.0",
    "babel-es6-polyfill": "1.1.0",
    "babel-jest": "16.0.0",
    "babel-loader": "6.2.5",
    "babel-plugin-react-display-name": "2.0.0",
    "babel-plugin-transform-async-to-generator": "6.8.0",
    "babel-plugin-transform-react-constant-elements": "6.9.1",
    "babel-plugin-transform-react-remove-prop-types": "0.2.9",
    "babel-preset-es2015": "6.16.0",
    "babel-preset-latest": "6.14.0",
    "babel-preset-react": "6.11.1",
    "babel-preset-react-hmre": "1.1.1",
    "babel-preset-stage-1": "6.13.0",
    "babel-register": "6.14.0",

 

{
  "presets": [
    "latest",
    "react",
    "stage-1"
  ]
}