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

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.

Related

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

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

How do I set up dynamic imports correctly (for beyond localhost)?

I followed https://docs.meteor.com/packages/dynamic-import.html to set up dynamic imports, and it works fine on localhost.
For context, I am creating a blog (Meteor/React/Apollo) which renders MDX files, and these files need to be imported, so I have a list of all my posts as such:
import("./imports/posts/61a000d03a1931b8819dc17e.mdx")
import("./imports/posts/619cae2f03f4ff710aa3d980.mdx")
import("./imports/posts/619e002d386ebf2023ea85c3.mdx")
import("./imports/posts/619fff7c5b312d7622acda86.mdx")
I have a Post.jsx component:
import React, { useState, useRef } from "react"
import { useHistory, useParams } from "react-router-dom"
import { useQuery } from "#apollo/client"
import { GET_POST_ID } from "../../api/posts/queries"
const Post = () => {
const Post = useRef()
const history = useHistory()
const { slug } = useParams()
const [loadedPost, setLoaded] = useState(false)
const [viewer, showViewer] = useState(false)
const open = () => showViewer(true)
const { data, loading, error } = useQuery(GET_POST_ID, { variables: { slug }})
if (loading) return null
if (error) {
console.log(error)
return null
}
import(`./posts/${data._id}.mdx`).then(MDX => {
Post.current = MDX.default
setLoaded(true)
}, (err) => {
console.log(err)
})
return loadedPost ? (
<>
<div className="postContent">
<div className="markdownOverride markdown-body">
<Post.current />
</div>
</div>
</>
) : null
}
export default Post
This works well and good on my local network. However, if I attempt to access it from outside my local network, an error is thrown in the console that all the blog modules are not found. The Apollo/GraphQL portion works fine, but the actual module can't be imported.
How do I get this to work outside of localhost?
Thanks.
EDIT: The error messages are, for each post:
Uncaught (in promise) Error: Cannot find module '/imports/posts/61a000d03a1931b8819dc17e.mdx`
And when I load the actual post page:
Uncaught (in promise) TypeError: Failed to fetch
Isn't your error thrown by console.log(err) ?
import(`./posts/${data._id}.mdx`).then(MDX => {
Post.current = MDX.default
setLoaded(true)
}, (err) => {
console.log(err) // <---- here
})
This means your path isn't right for /imports/posts/61a000d03a1931b8819dc17e.mdx.
To me you can't use changing parameters when doing dynamic imports.
./posts/${data._id}.mdx, because your meteor or webpack compilation needs to treat all the data._ids avalaible in your database in order to compile and prepare the file...
This might be why it works in development mode but not in production.
You can just do dynamic imports of modules or components (already compiled), no more to me. Take a look at your output compilation bundles, and try to find where are your components...
It turns out that I needed to specify the ROOT_URL correctly when initializing Meteor. With an ngrok http tunnel on port 3000 pointing to https://some-hash.ngrok.io, I had to start Meteor with: ROOT_URL="https://some-hash.ngrok.io" meteor. When I do this, I can access it fine and everything loads from my local IP and the ngrok URL, but I can't seem to load it up from localhost (it times out).
Specifying my local or public IP did not work, I could not get it to load through any of those methods.

Issue using axios in react [duplicate]

This question already has answers here:
Webpack 5 Receiving a Polyfill Error?!?! My JavaScript React project is receiving a polyfill error while trying to compile my webpack.config.js file
(3 answers)
Closed 10 months ago.
I can't seem figure out what's causing the following issue when using axios:
ERROR in ./node_modules/axios/lib/adapters/xhr.js 17:10-24
Module not found: Error: Can't resolve 'url' in 'C:\Users...
BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.
If you want to include a polyfill, you need to:
- add a fallback 'resolve.fallback: { "url": require.resolve("url/") }'
- install 'url'
If you don't want to include a polyfill, you can use an empty module like this:
resolve.fallback: { "url": false }
webpack compiled with 1 error
So, I am using axios when a user submits a value via input field; It triggers the following function posting the data and retrieving the values from the backend based on the posted data.
import React, {useState } from 'react'
import axios from 'axios';
import {TextField } from "#mui/material";
function Model () {
const [input,setInput] = useState ('');
const keyPress = (e) => {
if(e.keyCode === 13 || e.key === 'Enter' ){
e.preventDefault();
setInput(e.target.value)
const data = e.target.value
axios.post('http://localhost:5000/Data',data)
.then( res => {
console.log(res)
}).catch((err) => {
console.log("Message is not set maybe bc of :",err);
})
}
}
// render() {
return (
<>
<div className='container'>
<div id='serachBoxConatiner'>
<TextField fullWidth label="Enter here..." id="fullWidth"
onChange={input}
onKeyPress={keyPress}
/>
</div>
</div>
</>
);
}
export default Model
I have tried to delete and reinstall axios, I tried to us npm install to see if I that would help but nothing worked so far.
Since e.target.value is going to be a string, you can't post that as an axios request payload. You need to send json objects as exampled here. Can you try something like this (depending on what is the keyword for your endpoint):
axios.post('http://localhost:5000/Data',{
search: data
})
.then( res => {
console.log(res)
}).catch((err) => {
console.log("Message is not set maybe bc of :",err);
})
Remember search is not necessary, it can be any name based on your endpoint

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)
});

Angular 2+ modal popup timer and redirect

I want to make a request on mongodb and while the request is loading I want a modal windows popup with a hourglass who leave when the request is ending and redirect on an other route if possible.
Angular 2+
NodeJS
MongoDB
I have the modal windows popup ready.
Edit : Easy way
I found by adding a "dialogRef.close() in the res"
this.countModelService.getCount(datas)
.subscribe(res =>
{
dialogRef.close();
});
This is more angular related than node.js ... Imagine you have your mongoDB request implemented as an angular service mongoService. Imagine, your popup is done with ng-bootstrap - NgbModal. Then the client side code could look like this:
import { Component, Inject, OnInit } from '#angular/core';
import { Router } from '#angular/router';
import { MongoService } from './services/mongo.service';
#Component({
selector: 'app-mycomp',
templateUrl: './mycomp.component.html',
styleUrls: ['./mycomp.component.scss']
})
export class MycompComponent implements OnInit, ... {
mr: NgbModalRef;
constructor(...
private mongo: MongoService,
private modalService: NgbModal,
...) {
}
ngOnInit() {
// some initialization ...
}
getFromDB() { // <--- this is the function you call when clicking your button
this.mr = this.modalService.open(content);
mongo.getData().subscribe(
data => {
// ... your data handling ...
this.mr.close();
this.router.navigate(['/anotherroute']);
},
error => {
// ... your error handling ...
this.mr.close();
}
)
}
}
CSS-Styling with hourglass should then be something like
...
cursor: wait;
...

Resources