Such a problem that when I try to simply connect mongoDB in react
import React, {Component} from 'react';
export default class App extends Component{
componentDidMount(){
const {MongoClient} = require('mongodb');
const client = new MongoClient('mongodb+srv://dafu4k:****#cluster0.jd26aac.mongodb.net/?retryWrites=true&w=majority');
const start = async () => {
try{
await client.connect();
console.log('Connected')
}
catch(e){
console.log(e)
}
}
start();
}
render(){
return (
<>
<h1>Home page</h1>
</>
)
}
}
Errors of the same type appear in the browser itself
Module not found: Error: Can't resolve 'os' in 'C:\Users\DaFu4\OneDrive\Рабочий >стол\mongotest\mongo-test\node_modules\ip\lib'
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: { "os": require.resolve("os-browserify/browser") }'
install 'os-browserify'
If you don't want to include a polyfill, you can use an empty module like this:
resolve.fallback: { "os": false }
They differ in that the last line has different keys (timers,crypto,http, etc.)
I watched how to connect mongoDB to react, everywhere they used a certain mongoose along with mongoDB, but I can’t understand, maybe it’s required to connect to react, or am I still doing something wrong? (in normal js everything works fine, the code has not changed)
src/index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
package.json
{
"name": "mongo-test",
"version": "0.1.0",
"private": true,
"dependencies": {
"#testing-library/jest-dom": "^5.16.4",
"#testing-library/react": "^13.3.0",
"#testing-library/user-event": "^13.5.0",
"crypto-browserify": "^3.12.0",
"mongodb": "^4.7.0",
"react": "^18.1.0",
"react-dom": "^18.1.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
We can not connect React JS to MongoDB because things don’t work like this.
First, we create a react app, and then for backend maintenance, we create API in node.js and express.js which is running at a different port and our react app running at a different port. for connecting React to the database (MongoDB) we integrate through API.
Check this link:
[1]: https://www.geeksforgeeks.org/how-to-connect-mongodb-with-reactjs/#:~:text=First%2C%20we%20create%20a%20react,MongoDB)%20we%20integrate%20through%20API.
React is not communicating directly with MONGODB (via mongoose). It interacts with nodejs/express which is the one to communicate with MONGODB.
The explanation for the steps are presented in what I find to be the clearest form, in MERN STACK TUTORIAL (MERN = Mongodb, Express, React and Nodejs),
especially as the most essential part doesn't exist in Geeks4Geeks' tutorial (the part where they show you an example code of index.html).
Good luck!
Related
I have just started learning react testing library with jest and created a sample application to mock the server.my node version is v16.13.0. However, I am getting following error "SyntaxError: Cannot use import statement outside a module". I even write import axios from './lib/axios' but I got the same error.
Jest encountered an unexpected token
Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.
Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.
By default "node_modules" folder is ignored by transformers.
Here's what you can do:
• If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/ecmascript-modules for how to enable it.
• If you are trying to use TypeScript, see https://jestjs.io/docs/getting-started#using-typescript
• To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
• If you need a custom transformation specify a "transform" option in your config.
• If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.
You'll find more details and examples of these config options in the docs:
https://jestjs.io/docs/configuration
For information about custom transformations, see:
https://jestjs.io/docs/code-transformation
Details:
D:\test-projects\icecream\node_modules\axios\index.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import axios from './lib/axios.js';
^^^^^^
SyntaxError: Cannot use import statement outside a module
> 1 | import axios from "axios";
| ^
2 | import { useEffect, useState } from "react";
3 | import { Row } from "react-bootstrap";
4 | import ScoopOption from "./ScoopOptions";
at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1728:14)
at Object.<anonymous> (src/pages/entry/Options.jsx:1:1)
my test
import Options from "../Options";
import { render, screen } from "#testing-library/jest-dom";
test("displays image for each scoop option from the server",async () => {
render(<Options optionType="scoop" />);
const scoopImages = await screen.findAllByRole("img", { name: /scoop$/i });
expect(scoopImages).toHaveLength(2);
});
this is some of my code (Options.jsx):
import axios from "axios";
const [items, setItems] = useState([]);
useEffect(() => {
axios
.get(`http://localhost:3030/${optionType}`)
.then((response) => setItems(response.data))
.catch((err) => {});
}, [optionType]);
my package.json is:
{
"name": "icecream",
"version": "0.1.0",
"private": true,
"type": "module",
"dependencies": {
"#babel/plugin-transform-modules-commonjs": "^7.20.11",
"#testing-library/jest-dom": "^5.16.5",
"#testing-library/react": "^13.4.0",
"axios": "^1.2.1",
"bootstrap": "^5.2.3",
"eslint-plugin-jest-dom": "^4.0.3",
"eslint-plugin-testing-library": "^5.9.1",
"msw": "^0.49.2",
"react": "^18.2.0",
"react-bootstrap": "^2.7.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"#babel/core": "^7.20.7",
"#babel/preset-env": "^7.20.2",
"#testing-library/user-event": "^14.4.3",
"babel-jest": "^29.3.1"
}
}
this error occurs in axios in 1.x.x version and it is because of the change of transpilers from babel to Common js.
I solved this problem by changing "test" in my package.json to:
"test": "react-scripts test --transformIgnorePatterns \"node_modules/(?!axios)/\"",
I'm trying to follow along with this youtube video https://youtu.be/tbvguOj8C-o?t=33570
I'm having issue at this point forward in the video until the next code update (Roughly one minute in)
Specifically, the creator is adding these changes which causes an Invalid Hook Call
import RadioButtonUncheckedIcon from '#mui/icons-material/RadioButtonUnchecked';
...
const capture = useCallback(() => {
const imageSrc = webcamRef.current.getScreenshot();
console.log(imageSrc);
}, [webcamRef]);
...
<RadioButtonUncheckedIcon
className='WebcamCapture__button'
onClick={capture}
/>
The full code for the file is here:
import React, {useCallback, useRef} from "react";
import Webcam from "react-webcam";
import RadioButtonUncheckedIcon from '#mui/icons-material/RadioButtonUnchecked';
const videoConstraints = {
width: 250,
height: 400,
facingMode: "user",
};
function WebcamCapture() {
const webcamRef = useRef(null);
const capture = useCallback(() => {
const imageSrc = webcamRef.current.getScreenshot();
console.log(imageSrc);
}, [webcamRef]);
return (
<div className="webcamCapture">
<Webcam
audio={false}
height={videoConstraints.height}
ref={webcamRef}
screenshotFormat="image/jpeg"
width={videoConstraints.width}
videoConstraints={videoConstraints}
/>
<RadioButtonUncheckedIcon
className='WebcamCapture__button'
onClick={capture}
/>
</div>
);
}
export default WebcamCapture;
The WebcamCapture component is used here:
import React from 'react';
import WebcamCapture from './WebcamCapture';
function App() {
return (
<div className="app">
<h1>Test build</h1>
<WebcamCapture />
</div>
);
}
export default App;
The error code displayed in the chrome console is this:
Warning: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.
This is my best guess for the issue. It's the first issue called that causes declerations to be null. The full error stacktrace can be found here: https://pastebin.com/UKQm9TYi
The package.json looks like this,
{
"name": "snapchat-clone",
"version": "0.1.0",
"private": true,
"dependencies": {
"#mui/base": "^5.0.0-alpha.91",
"#mui/icons-material": "^5.8.4",
"#mui/material": "^5.9.2",
"#reduxjs/toolkit": "^1.8.3",
"#testing-library/jest-dom": "^5.16.4",
"#testing-library/react": "^13.3.0",
"#testing-library/user-event": "^14.3.0",
"react": "^16.8.0",
"react-dom": "16.8.0",
"react-redux": "^8.0.2",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
To the best of my knowledge, React and the renderer are matching versions, I haven't violated the Rules of Hooks (most tentative!), and there is only one copy of React running in the app as every other call is dedupped.
I'm very new to React and Node.JS so any feedback or criticisms are welcome. Thank you for your time.
I found the issue to the problem. There was a missing dependency in the package.json that I hadn't noticed until I placed the code into a sandbox.
Specifically, it was
"#mui/icons-material": "5.8.4",
I'm having issues with react-bootstrap, specifically whenever I try and use a react-bootstrap tag, like <Row></Row>, I'm getting the "Invalid hook call" error on my app.
I've run npm ls and these are the packages/versions I currently have installed:
boostrap#4.6.0
react-bootstrap#1.6.1
react-dom#17.0.2
react#17.0.2
I've also followed the advice in the React documentation on this error and added logs to see if I've got duplicate copies of React, but the test is returning 'true' in the console.
Here's the package.json file in my project:
{
"name": "kanvaswebappr",
"version": "0.1.0",
"private": true,
"dependencies": {
"bootstrap": "^4.1.3",
"jquery": "^3.5.1",
"merge": "^1.2.1",
"oidc-client": "^1.9.0",
"react-router-bootstrap": "^0.25.0",
"react-router-dom": "^5.1.2",
"react-scripts": "^3.4.4",
"reactstrap": "^8.4.1",
"rimraf": "^2.6.2"
},
"devDependencies": {
"ajv": "^6.9.1",
"cross-env": "^5.2.0",
"typescript": "^3.7.5",
"eslint": "^6.8.0",
"eslint-config-react-app": "^5.2.0",
"eslint-plugin-flowtype": "^4.6.0",
"eslint-plugin-import": "^2.20.1",
"eslint-plugin-jsx-a11y": "^6.2.3",
"eslint-plugin-react": "^7.18.3",
"nan": "^2.14.1"
},
"peerDependencies": {
"react": "^16.0.0",
"react-dom": "^16.0.0"
},
"eslintConfig": {
"extends": "react-app"
},
"scripts": {
"start": "rimraf ./build && react-scripts start",
"build": "react-scripts build",
"test": "cross-env CI=true react-scripts test --env=jsdom",
"eject": "react-scripts eject",
"lint": "eslint ./src/"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
As you can see, I've moved react and reactdom into peeDependencies and then run npm install, but that hasn't helped either.
My app is currently super basic because I'm just starting out/learning.
My index.js file:
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter } from 'react-router-dom';
import App from './containers/App';
import registerServiceWorker from './registerServiceWorker';
import 'bootstrap/dist/css/bootstrap.css';
const baseUrl = document.getElementsByTagName('base')[0].getAttribute('href');
const rootElement = document.getElementById('root');
ReactDOM.render(
<BrowserRouter basename={baseUrl}>
<App />
</BrowserRouter>,
rootElement);
My App.js file:
import React, { Component } from 'react';
import './App.css';
import Layout from '../components/Layout/Layout';
class App extends Component {
render() {
return (
<Layout>
<strong>This content is going to be rendered as the props.children inside the Layout component.</strong>
</Layout>
);
}
}
export default App;
My Layout.js file:
import React from 'react';
import Alert from 'react-bootstrap/Alert';
const layout = (props) => {
return (
<div>
<div>
This is the place for the navigation component.
</div>
<Alert>
This is an alert—check it out!
</Alert>
<main>
{props.children}
</main>
</div>
)
}
export default layout;
If anyone is able to help I would be incredibly grateful!
I fixed it myself after a bit more messing around this morning. Posting this here in case it's of any use to anyone else.
I'm building my React app as part of an asp.net solution and I had a node_modules folder at both solution level and in my actual React app/project. I'm very new to all this so I think I'd managed to install packages in both places and they were out of sync in terms of what was installed and version numbers. I ran npm update at both levels to bring everything up to date and then I ran npm link MyApp/node-modules/react from the solution folder just to make sure that React wasn't being duplicated (although I don't think it was).
All seems to be working now.
solved it by going into node modules folder to check the versions react and react-dom installations. then I changed those that were behind. actually i deleted the node modules folder.
Other hooks in my components work normally, but useLocation throws an invalid hook call. To make sure this wasn't due to some obscure interference from weird logic in the rest of the app, I reduced the problem further and further untill I basically ended up with the example from the useLocation docs on https://reactrouter.com/web/api/Hooks and it still doesn't work. Here's my code:
import React from 'react'
import ReactDOM from 'react-dom'
// import App from "./App";
import { BrowserRouter as Router, Switch, useLocation, Route } from 'react-router-dom'
// import './index.scss'
// import * as serviceWorker from './serviceWorker'
// const dotenv = require('dotenv')
// ReactDOM.render(<App />, document.getElementById("root"));
function usePageViews() {
let location = useLocation()
console.log('===location===', location)
}
function App() {
usePageViews()
return (
<Switch>
...
{/* <Route path="*" component={() => <div>TEST</div>}></Route> */}
</Switch>
)
}
ReactDOM.render(
<Router>
<App />
</Router>,
document.getElementById('root')
)
I tryed all sorts of things but I don't know how to reduce the problem down from here. I used this hook before in a different project and it worked fine. I tried deleting my node_modules and package-lock.json and re-installing the packages and the same error persists. Here's my package.json:
{
"name": "personal_website",
"version": "0.1.0",
"private": true,
"dependencies": {
"#types/jest": "24.0.23",
"#types/node": "12.12.11",
"#types/react": "16.9.11",
"#types/react-dom": "16.9.4",
"react": "^16.12.0",
"react-dom": "^16.12.0",
"react-scripts": "3.2.0",
"typescript": "3.7.2"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"dotenv": "^8.2.0"
}
}
EDIT: It's clearly something to do with project setup. Obviously this code works for other people otherwise it wouldn't be there in the docs, and I set up a fresh project with the same code and it works. It's just that I have no clue what part of the project setup could cause this kind of issue.
I copied your code and it works without problems. Check here.
Maybe your usePageViews function isn't a valid React Component on your call context, which means that hooks won't work inside of it. You should do:
<usePageViews />
instead of:
usePageViews()
of course, this within the App return.
Ok, so I tracked it down. Turns out, I had react-router-dom installed further up in the project hierarchy (this app is the client app and it's inside of a larger project containing several apps and with its own package.json) but not in the local package.json. As you can see from the project.json i posted, react-router-dom isn't actually in there. The Router still worked, apparently succesfully working with the parent's node_modules but the hook threw this error which is very weird and unexpected. Hopefully this helps someone else having a simmilar problem.
I am a beginner in ReactJS. Just after finishing a course on the basics of React and Redux. I have started a new Udemy course entitled "React Data Visualization - Build a Cryptocurrency Dashboard." I am facing a problem in lecture 4 while trying to start the server with yarn start command:
Failed to compile
./src/index.js
Cannot find file: 'index.js' does not match the corresponding name on disk: '.\src\App\app'.
Here are my codes on index.js file under app directory:
import React, { Component } from 'react';
import './App.css';
class App extends Component {
render(){
return (
<div>
Hello World
</div>
);
}
}
export default App;
Here are my codes on index.js file under src directory:
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
ReactDOM.render(<App />, document.getElementById('root'));
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
How can I fix the issue?
You can find the project files here.
https://drive.google.com/open?id=1u-8mCYSWZtXPbIqELKsF33FOiXb3yrkH
Edit 1: I am adding the codes inside package.json file, as suggested by #Wesgur:
{
"name": "cryptodash",
"version": "0.1.0",
"private": true,
"dependencies": {
"#testing-library/jest-dom": "^4.2.4",
"#testing-library/react": "^9.3.2",
"#testing-library/user-event": "^7.1.2",
"react": "^16.12.0",
"react-dom": "^16.12.0",
"react-scripts": "3.4.0"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
Edit 2: I am adding the image to show the folder structure, as suggested by #Madhavan.V:
#Shawan It is just a typo change the App import statement in src/index from import App from './App'; to import App from './app';.
import App from './app';
this will import your index.js of app folder.