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:

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:

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

These other two files may help in setting up:

 

 

Shares

Published by

Code Review

Code Review

CodeReviewVideos is a video training site helping software developers learn Symfony faster and easier.

2 thoughts on “Using async / await with React”

  1. Hello, I would love to understand and implement Async Await features, I’m not sure if my code below is correct!

    export function actionModalAdicionarRegistro() {
    return (dispatch) => {
    try {
    const PEOPLES = db.ref().child('peoples')
    const REG = PEOPLES.push({'firstName':'Alexon', 'lastName':'Moreira'})
    dispatch({type:'ADD', payload: REG})
    dispatch(actionModalListarRegistro('PEOPLES'))
    dispatch(actionModalClose(false))
    }
    catch(e) {
    console.error(e.error)
    }
    }
    }

    bad, anyway, I still have the error:

    Uncaught ReferenceError: regeneratorRuntime is not defined

    My config to webpack:

    {test:/\.js?/i, loader:'babel-loader', exclude:/node_modules/, options:{presets:['env', 'react', 'stage-1'], plugins:['transform-async-to-generator', ['transform-decorators-legacy'], ['transform-object-rest-spread', {'useBuiltIns':true}]]}},

    So, how to make the code work, using the async, await resources?

Leave a Reply

Your email address will not be published. Required fields are marked *