React "The top-level-await experiment is not enabled" and "await"
Matthew Barrera
I need to await some data from another file but whenever I try to run following code, an error comes up. My Code:
import React from 'react';
import './App.css';
import { getApiData } from './functions/player-api-data'
export async function App() { const data = await (getApiData('a3d7dc03c0e84c3eaa726110df90cbf8', 'player') as any) console.log(await data) return ( <div className="App"> <pre>{JSON.stringify(await data)}</pre> </div> );
}
export default await App as anyThe Error:
Module parse failed: The top-level-await experiment is not enabled (set experiments.topLevelAwait: true to enabled it)
File was processed with these loaders: * ./node_modules/@pmmmwh/react-refresh-webpack-plugin/loader/index.js * ./node_modules/babel-loader/lib/index.js * ./node_modules/source-map-loader/dist/cjs.js
You may need an additional loader to handle the result of these loaders.
Error: The top-level-await experiment is not enabled (set experiments.topLevelAwait: true to enabled it)I have tried to find the webpack.config.js file but in the existing file, there's no "experiments" object to be found in it. If there is a better way than fixing this specific error that would be great too.
11 Answer
React Components Cannot be Asynchronous. If you want asyncronous data, you can use UseEffect. Modify your code as..
import React,{useEffect} from 'react';
import './App.css';
import { getApiData } from './functions/player-api-data' function App() { const [data,setData] = useState(); const getData = async () => { let result = await getApiData('a3d7dc03c0e84c3eaa726110df90cbf8', 'player') setData(result) } useEffect(() => { // Fetching Data on Initial Load getData() },[]) return ( <div className="App"> // will render if data is primitive or valid jsx <pre>{data}</pre> </div> );
}
export default App