React "The top-level-await experiment is not enabled" and "await" - node.js

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 any
The 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.

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

Related

use Effect not working in react. the error is saying Uexpected token in the web console

I am using use effect in react js and it seems that it has a problem if I use 'effect'
in my react app then it gives me an error saying "Unexpected token"
import React, { Component , useEffect} from 'react'
class Effect extends Component {
useEffect(() => {
console.log('Effect');
})
constructor() {
super()
this.state =
{
count :0
}
this.CH = () =>
{
this.setState(PS =>{
console.log(PS);
return {count:PS.count +1}
})
}
}
render()
{
return(
<>
<button onClick={this.CH}>
</button>
<p>
{`You have clicked me ${this.state.count} times.`}
</p>
</>
)
}
}
export default Effect
and this is the useEffect code:
useEffect(() => {
console.log('Effect');
})
so i followed some vids and it seems to not work for me
they were using this in function based component . but i am not,
so the the problem us this only?
You can only use useEffect on Functional-based components!
On class-based you have some alternatives: componentDidMount()
Docs: https://reactjs.org/docs/react-component.html#componentdidmount
Suggestion: if you are creating a new react app most of the time the best thing to do is to use function components.
Source: https://djoech.medium.com/functional-vs-class-components-in-react-231e3fbd7108#:~:text=The%20most%20obvious%20one%20difference,which%20returns%20a%20React%20element.

Firebase Realtime Database not working on NextJS only after build - Maximum call stack size exceeded

I used Firebase Realtime Database with Next.js, for back-end.
And I wrote the below code. But It works only in local, not in production. The reason I comments some lines as follows is that I want to show that the error was not caused by my code. onValue, get, set, update were all the same. The same error was raised. And also I confirmed that effect function in useEffect() runs only once.
/* lib/firebase.ts */
import { initializeApp } from 'firebase/app';
import { getDatabase } from 'firebase/database';
// Initialize Firebase
const firebaseConfig = {
...
};
const app = initializeApp(firebaseConfig);
// Initialize Realtime Database
export const database = getDatabase(app);
import { onValue, ref, update } from 'firebase/database';
import { database } from 'lib/firebase';
...
useEffect(() => {
onValue(
ref(database, `objects/${user.uid}`),
(snapshots) => {
console.log(snapshots);
// const fetchedObjects: Common.Object[] = [];
// snapshots.forEach((snapshot) => {
// fetchedObjects.push({ key: snapshot.key, ...snapshot.val() } as Common.Object);
// });
// setTimeout(() => {
// setObjects(fetchedObjects);
// setIsObjectLoaded(true);
// }, 500);
}
);
}, []);
As a result of console.log(), a snapshot object with no children was returned. But It should be a snapshot object with serveral child nodes according to database state. It is the case in local.
Only in production, the below error was raised. _app-e9aaf40698fc4780.js was bundled by Next.js, so It was so complicated that I couldn't read it. But when I deduce from comments, maybe it can be firebase/database code.
Uncaught RangeError: Maximum call stack size exceeded
at i (_app-e9aaf40698fc4780.js:1486:770)
at i (_app-e9aaf40698fc4780.js:1486:897)
at i (_app-e9aaf40698fc4780.js:1486:906)
at i (_app-e9aaf40698fc4780.js:1486:897)
at i (_app-e9aaf40698fc4780.js:1486:906)
at i (_app-e9aaf40698fc4780.js:1486:897)
at i (_app-e9aaf40698fc4780.js:1486:906)
at i (_app-e9aaf40698fc4780.js:1486:897)
at i (_app-e9aaf40698fc4780.js:1486:906)
at i (_app-e9aaf40698fc4780.js:1486:897)
1486 line's code is here.
*/ let e3,e4,e6=new class extends eW{compare(e,t){let n=e.node.getPriority(),r=t.node.getPriority(),i=n.compareTo(r);return 0===i?q(e.name,t.name):i}isDefinedOn(e){return!e.getPriority().isEmpty()}indexedValueChanged(e,t){return!e.getPriority().equals(t.getPriority())}minPost(){return eq.MIN}maxPost(){return new eq(j,new e2("[PRIORITY-POST]",e4))}makePost(e,t){let n=e3(e);return new eq(t,new e2("[PRIORITY-POST]",n))}toString(){return".priority"}},e5=Math.log(2);class e8{constructor(e){var t;this.count=parseInt(Math.log(e+1)/e5,10),this.current_=this.count-1;let n=parseInt(Array(this.count+1).join("1"),2);this.bits_=e+1&n}nextBitIsOne(){let e=!(this.bits_&1<<this.current_);return this.current_--,e}}let e9=function(e,t,n,r){e.sort(t);let i=function(t,r){let s=r-t,o,a;if(0===s)return null;if(1===s)return o=e[t],a=n?n(o):o,new eG(a,o.node,eG.BLACK,null,null);{let l=parseInt(s/2,10)+t,u=i(t,l),c=i(l+1,r);return o=e[l],a=n?n(o):o,new eG(a,o.node,eG.BLACK,u,c)}},s=new e8(e.length),o=function(t){let r=null,s=null,o=e.length,a=function(t,r){let s=o-t;o-=t;let a=i(s+1,o),u=e[s],c=n?n(u):u;l(new eG(c,u.node,r,null,a))},l=function(e){r?(r.left=e,r=e):(s=e,r=e)};for(let u=0;u<t.count;++u){let c=t.nextBitIsOne(),h=Math.pow(2,t.count-(u+1));c?a(h,eG.BLACK):(a(h,eG.BLACK),a(h,eG.RED))}return s}(s);return new eY(r||t,o)},e7,te={};class tt{constructor(e,t){this.indexes_=e,this.indexSet_=t}static get Default(){return(0,f.hu)(te&&e6,"ChildrenNode.ts has not been loaded"),e7=e7||new tt({".priority":te},{".priority":e6})}get(e){let t=(0,f.DV)(this.indexes_,e);if(!t)throw Error("No index defined for "+e);return t instanceof eY?t:null}hasIndex(e){return(0,f.r3)(this.indexSet_,e.toString())}addIndex(e,t){(0,f.hu)(e!==e$,"KeyIndex always exists and isn't meant to be added to the IndexMap.");let n=[],r=!1,i=t.getIterator(eq.Wrap),s=i.getNext();for(;s;)r=r||e.isDefinedOn(s.node),n.push(s),s=i.getNext();let o;o=r?e9(n,e.getCompare()):te;let a=e.toString(),l=Object.assign({},this.indexSet_);l[a]=e;let u=Object.assign({},this.indexes_);return u[a]=o,new tt(u,l)}addToIndexes(e,t){let n=(0,f.UI)(this.indexes_,(n,r)=>{let i=(0,f.DV)(this.indexSet_,r);if((0,f.hu)(i,"Missing index implementation for "+r),n===te){if(!i.isDefinedOn(e.node))return te;{let s=[],o=t.getIterator(eq.Wrap),a=o.getNext();for(;a;)a.name!==e.name&&s.push(a),a=o.getNext();return s.push(e),e9(s,i.getCompare())}}{let l=t.get(e.name),u=n;return l&&(u=u.remove(new eq(e.name,l))),u.insert(e,e.node)}});return new tt(n,this.indexSet_)}removeFromIndexes(e,t){let n=(0,f.UI)(this.indexes_,n=>{if(n===te)return n;{let r=t.get(e.name);return r?n.remove(new eq(e.name,r)):n}});return new tt(n,this.indexSet_)}}/**
I can't interpret the code, and I can't figure out the cause, so I'm going crazy. Help me.
+) I also tested on the new Next.js project created by create-next-app.
npx create-next-app#latest --typescript
cd {project folder name}
npm install firebase
And the code I wrote is here.
import "../styles/globals.css";
import type { AppProps } from "next/app";
import { useEffect } from "react";
import { initializeApp } from "firebase/app";
import { getDatabase, onValue, ref } from "firebase/database";
function MyApp({ Component, pageProps }: AppProps) {
useEffect(() => {
const firebaseConfig = {
...
};
const app = initializeApp(firebaseConfig);
const db = getDatabase(app);
// It works only in local
onValue(ref(db, "???"), (snapshots) => console.log(snapshots));
}, []);
return <Component {...pageProps} />;
}
export default MyApp;
As a result, like my project, the same error was raised. But It works well in local.
I'm the author of this post.
I resolved this problem by downgrading Next.js version from 12.3.1 to 12.3.0.

Create React App and JEST property matchers

I've got this component that I've simplified for this example as part of a bigger create react app
import React from 'react';
function myVersion() {
return (
<p className={'ActivateSound--para'} data-testid={`version`}>
Version {process.env.REACT_APP_VERSION} has loaded, congrats!
</p>
);
}
export { myVersion };
and in the env I get the version from package.json
REACT_APP_VERSION=$npm_package_version
but in the test I've got
import React from 'react';
import { myVersion } from '../components/my-version';
import { render, screen, cleanup, fireEvent } from '#testing-library/react';
afterEach(cleanup);
describe('my version component', () => {
test('snapshot hasnt changed', () => {
expect(container.firstChild).toMatchSnapshot();
});
});
I am now looking at https://jestjs.io/docs/snapshot-testing#property-matchers. It seems I can exclude the version number somehow, I've tried a bunch of attempts but it's not ignoring the version number
expect(container.firstChild).toMatchSnapshot({
screen.getByTestId('version'): expect.any(String)
});

How to use react-intl with jest

I'm working with React Testing Library an I need to get the translation for a text, we mocked in our setupTest file the react-intl library:
jest.mock('react-intl', () => {
const reactIntl = require.requireActual('react-intl');
const intl = reactIntl.createIntl({
locale: 'en'
});
return {
...reactIntl,
useIntl: () => intl
};
});
but I don't know how to use it in the test, could someone provide me an complete examble of a test using the library to get a translation, please?
I tried to do it in this way:
let intl = useIntl();
let i18n = {
header: intl.formatMessage({
id: 'header.myHeader',
defaultMessage: 'header.myHeader'
})
};
but there are any messages in intl from the locales.
Regards.
Don't mock it, try and directly wrap your component with IntlProvider, or even better, create a helper render where you wrap with IntlProvider and render it with that:
import {IntlProvider} from 'react-intl`;
import {render} from '#testing-library/react';
const renderWithReactIntl = (component, locale, messages) => {
return render(<IntlProvider locale={locale} messages={messages}>
{component}
</IntlProvider>
);
};
Within your test() or it() just wrap your unconnected component in renderWithReactIntl:
const { /testing library selector goes here/ }
= renderWithReactIntl(<YourComponent />, messages, locale)

Test callback prop with Enzyme

I have React-Spring animation in my component:
<SpinnerKf state={status} onRest={changeView && status === 'SUCCESS' ? () => changeView(VIEW_MODES.RECEIPT) : null}>
....
</SpinnerKf>
Where I pass function call inside onRest prop - this is the prop from React-Spring Keyframe, which is called after animation end.
How can I cover this with a test? I'm opened for any tricks, just need to avoid complaining in test coverage.
You can use Enzyme to get the SpinnerKf component and then call its onRest property directly.
Here is a simplified example:
code.js
import * as React from 'react';
const SpinnerKf = () => null;
export const Component = () => (<SpinnerKf onRest={() => { return 'does something'; }}/>);
code.test.js
import * as React from 'react';
import { shallow } from 'enzyme';
import { Component } from './code';
test('callback', () => {
const wrapper = shallow(<Component />);
const result = wrapper.find('SpinnerKf').props().onRest();
expect(result).toBe('does something'); // Success!
});
Note that testing the return value or behavior of the callback is optional, as long as it runs during a unit test it will be included in the code coverage report.

Resources