Trying to use async/await in my React app gave me this error Uncaught ReferenceError: regeneratorRuntime is not defined. I found two solutions
[topads][/topads]
First, this is the code I was trying to run
require("whatwg-fetch"); const ROOT_API_URL = "https://api.github.com/"; const ACCESS_TOKEN = "access_token=9d...c0"; const fetchUser = async () => { const url = `${ROOT_API_URL}user?${ACCESS_TOKEN}`; const response = await fetch(url); const body = await response.json(); if (response.status !== 200) throw Error(body.message); return body; }; module.exports = { fetchUser, };
And the error
Solution 1
Use babel-preset-env. If you are using babel-preset-es2015, just replace it with babel-preset-env and you will get the latest Babel plugins support.
// If you are using ES2015 preset yarn remove babel-preset-es2015 yarn add -D babel-preset-env
Then add the following Babel configuration via .babelrc
{ "presets": [ "env", { "targets": { "browsers": [ "last 2 Chrome versions" ] } } ] }
Solution 2
You will need a polyfill for browser support and have the regeneratorRuntime.
Install the following two packages
yarn add -D babel-plugin-transform-regenerator yarn add babel-polyfill
Add the following Babel configuration via .babelrc
{ "plugins": ["transform-regenerator"] }
In your webpack configuration add
module.exports = { entry: ["babel-polyfill", "./app/js"] };
Note: babel-polyfill needs to be before your main app JavaScript entry.
And finally import the polyfill in your top-most container
... import 'babel-polyfill'; ...
Now async/await should be working.
[Source]
babel-plugin-transform-regenerator
babel-polyfill
[bottomads][/bottomads]
Good job abs how you track the scammers.. And I love what you doing. But please I want to be a hacker and I want you to teach me. Thanks
Second solution is working for me. Thank you.
Excellent…second solution works for me using Babel 7 (too). FYI, you don’t need both the webpack entry and the root level import.
First Solution, .babelrc file is missing a close “]” for “presets”
2nd Solution worked for me.. Thanks !!