javascript - How to allow async functions in React + Babel? - Stack Overflow

I have a TypescriptReact app, that can perform async function with a thencatch promise, but not with

I have a Typescript/React app, that can perform async function with a then/catch promise, but not with async/await/try/catch.

The error is: Uncaught ReferenceError: regeneratorRuntime is not defined .

The error seems to e from Babel. Here is my config:

{
  "presets": [
    "@babel/preset-env",
    "@babel/preset-typescript",
    "@babel/preset-react"
  ],
  "plugins": ["babel-plugin-styled-ponents"]
}

I have a Typescript/React app, that can perform async function with a then/catch promise, but not with async/await/try/catch.

The error is: Uncaught ReferenceError: regeneratorRuntime is not defined .

The error seems to e from Babel. Here is my config:

{
  "presets": [
    "@babel/preset-env",
    "@babel/preset-typescript",
    "@babel/preset-react"
  ],
  "plugins": ["babel-plugin-styled-ponents"]
}

How to fix this?

Share Improve this question asked Apr 19, 2020 at 12:12 DoneDeal0DoneDeal0 6,29718 gold badges77 silver badges132 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 9

You can find your solution at here

If I summarise then you have to install a babel plugin named plugin-transform-runtime and need to configure the .babelrc settings.

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

After installing these two go to the .babelrc file and add these plugins.

"plugins": [
    ["@babel/plugin-transform-runtime",
      {
        "regenerator": true
      }
    ]
  ],

for babel 7

All necessary packages are included in "@babel/preset-env"

{
    "presets": [
        [
            "@babel/preset-env",
            {
                "targets": {
                    "node": "10.0.0"
                }
            }
        ],
        "@babel/preset-react"
    ]
}

Super Basic example

import React from "react";

const Board = () => {

    const [resp_post, setResp_post] = React.useState(0);

    (async function getData() {
        setResp_post(await Promise.resolve(30));
    })();
    
    return <h1>Board {resp_post} {value}</h1>;
};

export default Board;

preset-env documentation

preset-reactlink documentation

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1743733991a4497922.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信