React Memory Usage Deploying onto Heroku - reactjs

I have recently completed a MERN stack web application and trying to deploy it on to Heroku. It looks like it's deployed but when I try to login or create user, it says 404 not found /graphql. When running heroku log --tails, it says after the post the app crashes due to memory usage over quota.
So I ran it locally and used DevTools to look at the memory usage. I noticed there were huge spikes for login, login, searching because it loops and populates the page with items for api. I am currently trying to refactor the searched and use react.lazy to only show what's in viewpoint of user. But as for login and signup, I really have no idea how to refactor it to use less memory.
This is my code for the frontend of login:
LoginPage.js
import { Link } from 'react-router-dom';
import { useMutation } from '#apollo/client';
import { authService } from '../utils/auth';
import { LoginForm } from '../components/Login/LoginForm'
import { Alert } from 'react-bootstrap';
import { LOGIN_USER } from '../utils/mutations';
export const Login = (props) => {
const [formState, setFormState] = useState({ email: '', password: '' });
const [login, { error }] = useMutation(LOGIN_USER);
const handleSubmit = (e) => {
const { name, value } = e.target;
setFormState({
...formState,
[name]: value,
});
};
// submit form
const handleFormSubmit = async (e) => {
e.preventDefault();
console.log(formState);
if (!formState.email || !formState.password) {
alert('Failed to submit form! Please fill all requested fields.');
document.location.replace('/');
}
try {
const { data } = await login({
variables: { ...formState },
});
authService.login(data.login.token)
} catch (e) {
console.log(e);
}
// clear form values
setFormState({
email: '',
password: '',
});
};
return (
<> {authService.loggedIn() ? (
<p>
Success! You may now head{' '}
<Link to="/">back to the homepage.</Link>
</p>
) : (
<LoginForm
onSubmit={handleFormSubmit}
handleSubmit={handleSubmit}
handleFormSubmit={handleFormSubmit}
formState={formState}
/>
)}
{error && (
<Alert severity='error'>
{error.message}
</Alert>
)}
</>
);
};
export default LoginForm;
LoginForm.js
import React from 'react'
import { Form, Button } from 'react-bootstrap';
export const LoginForm = ({handleFormSubmit, handleSubmit, formState}) => {
return (
<Form onSubmit={handleFormSubmit} style={{padding:'15%', justifyContent:'center'}}>
<Form.Group>
<Form.Label htmlFor='email'>Email</Form.Label>
<Form.Control
type='email'
placeholder='Your email'
name='email'
onChange={handleSubmit}
value={formState.email}
required
/>
<Form.Control.Feedback type='invalid'>Email is required!</Form.Control.Feedback>
</Form.Group>
<Form.Group>
<Form.Label htmlFor='password'>Password</Form.Label>
<Form.Control
type='password'
placeholder='Your password'
name='password'
onChange={handleSubmit}
value={formState.password}
required
/>
<Form.Control.Feedback type='invalid'>Password is required!</Form.Control.Feedback>
</Form.Group>
<Button style={{margin:'5%', justifyContent:'center', textAlign:'center'}}
disabled={!(formState.email && formState.password)}
type='submit'
variant='success'>
Submit
</Button>
</Form>
)
}
package.json in client
{
"name": "client",
"version": "0.1.0",
"private": true,
"engines": {
"node": "14.2.0",
"npm": "6.14.5"
},
"dependencies": {
"#apollo/client": "^3.7.3",
"#apollo/react-hooks": "^4.0.0",
"#testing-library/jest-dom": "^5.16.5",
"#testing-library/react": "^13.4.0",
"#testing-library/user-event": "^13.5.0",
"apollo-cache-inmemory": "^1.6.6",
"apollo-cache-persist": "^0.1.1",
"apollo-client": "^2.6.10",
"apollo-link-http": "^1.5.17",
"apollo-link-rest": "^0.9.0",
"axios": "^1.2.2",
"bootstrap": "^5.2.3",
"graphql": "^15.8.0",
"http-proxy-middleware": "^2.0.6",
"jwt-decode": "^3.1.2",
"qs": "^6.11.0",
"react": "^18.2.0",
"react-bootstrap": "^2.7.0",
"react-dom": "^18.2.0",
"react-moment": "^1.1.3",
"react-router-dom": "^6.7.0",
"react-scripts": "^5.0.1",
"react-use": "^17.4.0",
"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"
]
},
"main": "index.js"
}
package.json in server
"name": "server",
"version": "1.0.0",
"description": "",
"main": "server.js",
"scripts": {
"start": "node server.js",
"watch": "nodemon server.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"apollo-server-express": "^3.11.1",
"axios": "^1.2.5",
"bcrypt": "^5.1.0",
"cors": "^2.8.5",
"dotenv": "^16.0.3",
"express": "^4.18.2",
"graphql": "^16.6.0",
"jsonwebtoken": "^9.0.0",
"mongoose": "^6.9.0",
"nodemon": "^2.0.20"
}
}
Package.json in root
{
"name": "foodgenie",
"version": "1.0.0",
"description": "",
"main": "server/server.js",
"scripts": {
"start": "if-env NODE_ENV=production && npm run start:prod || npm run start:dev",
"start:prod": "cd server && npm start",
"start:dev": "concurrently \"cd server && npm run watch\" \"cd client && npm start\"",
"install": "cd server && npm i && cd ../client && npm i",
"heroku-postbuild": "NPM_CONFIG_PRODUCTION=false npm install --prefix client && npm run build --prefix client"
},
"keywords": [],
"author": "Chris H",
"license": "ISC",
"dependencies": {
"concurrently": "^7.6.0",
"dotenv": "^16.0.3",
"if-env": "^1.0.4",
"nodemon": "^2.0.20"
}
}
Procfile
web: npm run start:dev
Any advice or feedback will be greatly appreciated. Thank you.

Related

React can't recognize firebase/auth or #firebase/auth

I am having an issue that I can't figure out the solution, I built this page a while ago, and now I need to add an authentication section, I already had the firebase installed because of the deployment, so I as I wrote the code most of the methods wouldn't be recognized or appear. I tried to look for solutions, used firebase/compat/auth
but nothing. This is the code I have
the Firebase config file:
import firebase from 'firebase/app';
import 'firebase/firestore';
const firebaseConfig = {
apiKey: "xxxx",
authDomain: "xxx",
projectId: "xxx",
storageBucket: "xxxx",
messagingSenderId: "xxx",
appId: "xxx",
measurementId: "xxxx"
};;
const firebaseApp=firebase.initializeApp(firebaseConfig);
const db=firebase.firestore();
const auth = firebase.auth(firebaseApp);
export { auth }
export default db;
The implementation
import React, { useState } from 'react'
import {auth} from '../../firebase.config.js'
import {onAuthStateChanged,signInWithEmailAndPassword,signOut} from "firebase/auth"
function AppAuthentication(){
const [loginEmail,setLoginEmail] = useState("");
const [loginEmailPass, setLoginEmailPass] = useState("");
const [user,setUser] = useState({});
const login = async () => {
try{
const user = await signInWithEmailAndPassword(auth,loginEmail,loginEmailPass);
console.log(user)
}catch(error){
console.log(error)
}
}
const logout = async () => {
await signOut(auth)
}
return(
<>
<div>
<h3> Login</h3>
<br></br>
<input placeholder='Your email'
onChange={(event)=>{
setLoginEmail(event.target.value);
}}
/>
<br></br>
<input placeholder='Your Password'
onChange={(event)=>{
setLoginEmailPass(event.target.value)
}}
/>
<br></br>
<button onClick={login}>Login</button>
<br></br>
<h4>User:</h4>
<br></br>
<button onClick={logout}>Sign Out</button>
</div>
</>
)
}
export default AppAuthentication;
The Error message I get is:
Module '"firebase/auth"' has no exported member 'onAuthStateChanged'.
Module '"firebase/auth"' has no exported member 'signOut'.
This is the package.json
"dependencies": {
"#craco/craco": "^6.2.0",
"#firebase/auth": "^0.20.7",
"#testing-library/jest-dom": "^5.14.1",
"#testing-library/react": "^11.2.7",
"#testing-library/user-event": "^12.8.3",
"#types/jest": "^26.0.24",
"#types/node": "^12.20.19",
"#types/react": "^17.0.18",
"#types/react-dom": "^17.0.9",
"firebase": "^8.10.1",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-dropdown": "^1.9.2",
"react-icons": "^4.2.0",
"react-router-dom": "^5.2.0",
"react-scripts": "4.0.3",
"typescript": "^4.3.5",
"web-vitals": "^1.1.2"
},
"scripts": {
"start": "craco start",
"build": "craco build",
"test": "craco test",
"eject": "react-scripts eject",
"deploy:firebase": "npm run build && firebase deploy"
},
"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"
]
},
"devDependencies": {
"#types/react-router-dom": "^5.1.8",
"autoprefixer": "^9.8.6",
"postcss": "^7.0.36",
"tailwindcss": "npm:#tailwindcss/postcss7-compat#^2.2.7"
}
}
Thanks in advance for thee help. my Firebase version in 8.10.1

Deploying React, Express project to Heroku

I have created a small React Express app and am struggling with deploying it to Heroku.
So far I have organised the client and server into separate folders.
Previously I had the contents of server in the projects root and client as its own folder accessed with a path.join however this didn't serve any of the build files so I opted to separate the folders.
Now with two folders I use a root package.json to install all dependencies and get both sides running.
{
"name": "project",
"version": "1.0.0",
"main": "",
"scripts": {
"start": "npm start --prefix server",
"install-client": "cd client && npm install && npm run build && cd ..",
"install-server": "cd server && npm install && cd .. ",
"heroku-postbuild": "npm run install-client && npm run install-server"
}
}
This works with my other folders in serving the back-end however there is no front-end at all. I'm wondering if there is a solution to this problem specifically or even a better way to deploy a full stack project in the same dyno.
This is my currently result on my Heroku app:
Heroku app result
And here any additional relevant files:
Main server file
const express = require('express');
const path = require('path');
const cors = require('cors');
const db = require('./config/db');
const app = express();
const PORT = process.env.PORT || 8080;
//Dependencies
app.use(express.json());
app.use(cors());
//Select all rows from table
app.get('/api/get', (req, res) => {
const selectAll = 'SELECT * FROM plant_data';
db.query(selectAll, (err, rows) => {
if (err) throw err;
res.send(rows);
});
});
//Insert into database
app.post('/api/insert', (req, res) => {
const row = req.body.row;
const insert = "INSERT INTO plant_data (test) VALUES (?)";
db.query(insert, [row], (err, rows) => {
if (err) throw err;
console.log("inserted: " + row);
});
});
//Server port
app.listen(process.env.PORT || PORT, () => {
console.log('Server started on port ' + PORT);
});
Main client file
import React, {useState, useEffect} from "react";
import axios from "axios";
export default function Index() {
const [data, setData] = useState('');
const [rows, setRows] = useState([]);
useEffect(() => {
axios.get('/api/get')
.then(res => {
setRows(res.data);
}).catch(err => {
console.log(err);
});
});
//Connects front-end submit to backend db
const insertRow = () => {
axios.post('/api/insert', {
row: data
});
};
return (
<>
<h1>Body</h1>
<input type="text" onChange={(e) => {
setData(e.target.value);
}} />
<button onClick={insertRow}>Submit</button>
{rows.map((row) => {
return <p>{row.test}</p>
})}
</>
);
};
Server package file:
{
"name": "server",
"version": "1.0.0",
"description": "",
"main": "app.js",
"scripts": {
"start": "node server.js",
"dev": "nodemon server.js",
"heroku-postbuild": "npm install --prefix client && npm run build --prefix client"
},
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.20.0",
"cors": "^2.8.5",
"express": "^4.18.1",
"mysql": "^2.18.1",
"nodemon": "^2.0.19"
}
}
Client package file:
{
"name": "client",
"version": "0.1.0",
"private": true,
"dependencies": {
"#emotion/react": "^11.8.2",
"#material-ui/core": "^4.12.3",
"#mui/material": "^5.5.3",
"#testing-library/jest-dom": "^5.16.2",
"#testing-library/react": "^12.1.4",
"#testing-library/user-event": "^13.5.0",
"axios": "^0.27.2",
"hamburger-react": "^2.4.1",
"node-sass": "^7.0.1",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-helmet": "^6.1.0",
"react-router-dom": "^6.2.2",
"react-scripts": "5.0.0",
"styled-components": "^5.3.5",
"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"
]
}
}

React App Keep Reloading until it get crashed

I am new to react js, I created a react app, and whenever I try to open the app it continuously reloads. can anyone help me in this? i tried but unable to find out any perfect solution.
Any solution?
package.json
{
"name": "sf",
"author": "KKK Team",
"version": "0.0.1",
"private": true,
"homepage": "/sfrs",
"scripts": {
"start": "env-cmd -f .env.development react-scripts start",
"build:development": "env-cmd -f .env.development react-scripts build",
"build:nonprod": "env-cmd -f .env.nonprod react-scripts build",
"build:production": "env-cmd -f .env.production react-scripts build",
"build": "react-scripts build",
"test": "jest --verbose",
"test:dev": "jest",
"test:watch": "jest --silent --watchAll",
"test:coverage": "jest --silent --coverage",
"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"
]
},
"dependencies": {
"#date-io/date-fns": "^1.3.13",
"#emotion/react": "^11.7.1",
"#emotion/styled": "^11.6.0",
"#material-table/core": "^0.2.20",
"#mui/icons-material": "^5.3.1",
"#mui/lab": "^5.0.0-alpha.66",
"#mui/material": "^5.3.1",
"#mui/styles": "^5.3.0",
"axios": "^0.25.0",
"buffer": "^6.0.3",
"clsx": "^1.1.1",
"crypto-browserify": "^3.12.0",
"env-cmd": "^10.1.0",
"jsonwebtoken": "^8.5.1",
"lodash": "^4.17.21",
"moment": "^2.29.1",
"msal": "^1.4.16",
"prop-types": "^15.8.1",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-perfect-scrollbar": "^1.5.8",
"react-redux": "^7.2.6",
"react-router": "^6.2.1",
"react-router-dom": "^6.2.1",
"recompose": "^0.30.0",
"redux": "^4.1.2",
"redux-logger": "^3.0.6",
"redux-thunk": "^2.4.1",
"stream-browserify": "^3.0.0",
"sweetalert2": "^11.4.8",
"sweetalert2-react-content": "^4.2.0",
"util": "^0.12.4",
"validator": "^13.7.0",
"web-vitals": "^2.1.4"
},
"devDependencies": {
"#testing-library/jest-dom": "^5.16.1",
"#testing-library/react": "^12.1.2",
"#testing-library/user-event": "^13.5.0",
"eslint": "^7.11.0",
"eslint-config-airbnb": "^18.2.0",
"eslint-config-prettier": "^6.11.0",
"eslint-plugin-import": "^2.22.0",
"eslint-plugin-jsx-a11y": "^6.3.1",
"eslint-plugin-prettier": "^3.1.4",
"eslint-plugin-react": "^7.20.3",
"eslint-plugin-react-hooks": "^4.0.8",
"husky": "^4.2.3",
"jest-canvas-mock": "^2.3.1",
"lint-staged": "^10.0.8",
"prettier": "^1.19.1",
"react-error-overlay": "^6.0.9",
"react-scripts": "4.0.3"
},
"jest": {
"setupFiles": [
"jest-canvas-mock"
]
},
"husky": {
"hooks": {
"pre-commit": "lint-staged",
"pre-push": "npm run test"
}
},
"lint-staged": {
"src/**/*.{js,jsx,json,css}": [
"prettier --write",
"eslint --fix"
]
},
"babel": {
"presets": [
"#babel/preset-react",
[
"#babel/preset-env",
{
"targets": {
"node": "current"
}
}
]
],
"plugins": [
[
"#babel/plugin-proposal-class-properties",
{
"loose": true
}
]
]
},
"resolutions": {
"react-error-overlay": "6.0.9"
}
}
I am using MUI 5. I have tried with upgrading and degrading the node version but unable to solve the issue.
app.jsx
import 'react-perfect-scrollbar/dist/css/styles.css';
import React, { useEffect } from 'react';
import { useRoutes } from 'react-router-dom';
import _ from 'lodash';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import { ThemeProvider } from '#mui/material';
import AuthProvider from './components/auth_provider';
import GlobalStyles from './components/globalstyles';
import theme from './theme/theme';
import AuthenticationProgressLoader from './components/authentication_progress_loader';
import UnAuthorized from './components/unauthorized';
import routeManager from './lib/route.manager';
import Alerts from './components/c_alert';
import PageProgress from './components/c_page_progress';
import PermissionManager from './lib/permission.manager';
const App = props => {
const {
userAccount,
userPermissions,
graphProfile,
routesConfig,
alerts,
isPageLoader
} = props;
const routing = useRoutes(routesConfig || []);
useEffect(() => {
if (
!_.isEmpty(userPermissions) &&
PermissionManager.isUserMerchant() &&
_.isEmpty(routesConfig)
) {
routeManager.dispatchRoutes();
}
}, [routesConfig, userPermissions]);
return !userPermissions ||
(!_.isEmpty(userPermissions) && !PermissionManager.isUserMerchant()) ? (
<UnAuthorized />
) : (
<ThemeProvider theme={theme}>
<GlobalStyles />
{!_.isEmpty(alerts.message) && <Alerts />}
{isPageLoader && <PageProgress />}
{userAccount && graphProfile && !_.isEmpty(userPermissions) ? (
routing
) : (
<AuthenticationProgressLoader />
)}
</ThemeProvider>
);
};
App.propTypes = {
// eslint-disable-next-line react/forbid-prop-types
userAccount: PropTypes.object,
// eslint-disable-next-line react/forbid-prop-types
graphProfile: PropTypes.object,
// eslint-disable-next-line react/forbid-prop-types
userPermissions: PropTypes.object,
// eslint-disable-next-line react/forbid-prop-types
routesConfig: PropTypes.array,
// eslint-disable-next-line react/forbid-prop-types
alerts: PropTypes.object,
isPageLoader: PropTypes.bool
};
App.defaultProps = {
userAccount: {},
graphProfile: {},
userPermissions: {},
routesConfig: [],
alerts: {},
isPageLoader: false
};
function mapStatesToProps(state) {
const { userPermissions, graphProfile, userAccount } = state.auth;
const { routesConfig } = state.routes;
const { alerts } = state;
const { isPageLoader } = state.pageProgress;
return {
userPermissions,
graphProfile,
userAccount,
routesConfig,
alerts,
isPageLoader
};
}
const authApp = AuthProvider(App);
const connectedApp = connect(mapStatesToProps, null)(authApp);
// eslint-disable-next-line
export { connectedApp as App };

how to use fetch with express to send data to express server that is using typescript?

I am getting a POST http://localhost:3000/handledata 500 (Internal Server Error)
when I am trying to post some data that I need to handle on the backend , below is the code for my front and backend anything missing ? or is there something wrong ? why would the post post to port 3000 instead of 5000 ? in my package.json I am calling a proxy is this even related to the error ?
// Fetch front end call
fetch('/handledata', {
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
method: 'POST',
body: JSON.stringify({ a: 1, b: 2 }),
})
.then((res) => {
console.log(res);
})
.catch((err) => {
console.log(err);
});
// Express server
import express from 'express';
import bodyParser from 'body-parser';
//import cors from 'cors'
import CryptoJs from 'crypto-js';
const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.json());
const PORT = 5000; //process.env.PORT || 5000;
const router = express.Router();
// Test server
app.get('/test', (request: any, response: any) => {
response.send('working......................');
});
// Post data to handle
app.post('/handledata', (req: any, res: any) => {
console.log(req.body);
const handeleddata = // handledata logic could be anything !
res.json(handeleddata);
});
app.listen(PORT, console.log(`Server Started on Port ${PORT}`)!);
frontend package.json
{
"name": "app",
"version": "0.1.0",
"private": true,
"dependencies": {
"#emotion/react": "^11.7.1",
"#emotion/styled": "^11.6.0",
"#material-ui/core": "^4.12.3",
"#material-ui/icons": "^4.11.2",
"#material-ui/lab": "^4.0.0-alpha.60",
"#paypal/react-paypal-js": "^7.5.1",
"#testing-library/jest-dom": "^5.16.2",
"#testing-library/react": "^12.1.3",
"#testing-library/user-event": "^13.5.0",
"#types/html2canvas": "^1.0.0",
"#types/jest": "^27.4.1",
"#types/jspdf": "^2.0.0",
"#types/node": "^16.11.26",
"#types/react": "^17.0.39",
"#types/react-dom": "^17.0.13",
"#types/react-router-dom": "^5.3.2",
"#types/uuid": "^8.3.3",
"axios": "^0.26.0",
"firebase": "^9.6.7",
"firestore-size": "^2.0.7",
"html2canvas": "^1.3.3",
"jspdf": "^2.4.0",
"notistack": "^1.0.10",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-ga": "^3.3.0",
"react-router-dom": "^5.3.0",
"react-scripts": "5.0.0",
"typescript": "^4.4.4",
"uuid": "^8.3.2",
"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"
]
},
"proxy": "http://localhost:5000"
}
Backend package.json
{
"name": "app",
"version": "1.0.0",
"engines": {
"node": "14.17.4",
"npm": "6.14.14"
},
"description": "",
"main": "index.js",
"scripts": {
"start": "node dist/server.js",
"client": "npm start --prefix client",
"clientinstall": "npm install --prefix client",
"dev": "concurrently \"nodemon src/index.ts\" \"npm run client\"",
"build": "tsc -p .",
"heroku-postbuild": "npm run build && NPM_CONFIG_PRODUCTION=false npm install --prefix client && npm run build --prefix client"
},
"author": "me",
"license": "ISC",
"dependencies": {
"bcryptjs": "^2.4.3",
"client": "file:client",
"config": "^3.3.6",
"crypto-js": "^4.1.1",
"express": "^4.17.1",
"express-validator": "^6.12.1",
"firebase": "^9.6.7",
"jsonwebtoken": "^8.5.1",
"mongoose": "^6.0.6",
"npm": "^8.1.4",
"ts-node": "^10.5.0",
"typescript": "^4.4.4"
},
"devDependencies": {
"#types/crypto-js": "^4.1.1",
"#types/express": "^4.17.13",
"#types/node": "^17.0.18",
"concurrently": "^6.2.1",
"nodemon": "^2.0.12"
}
}
You need to modify your fetch request API url to give the complete hostname:
fetch('http://localhost:5000/handledata')
also you need to setup the cors in your backend
app.use(cors());

How to fix an error with shallow Enzyme in testing ReactJS App

I want to test if my component displayed and I have an error with shallow (see an image of error).
I am using :
"enzyme": "^3.10.0",
"enzyme-adapter-react-16": "^1.14.0",
"jest-enzyme": "^7.1.1",
"jest": "^24.8.0"
My test look:
import React from "react";
import { shallow } from "enzyme";
import Header from "./Header";
describe("Header Component", () => {
it("Should render without errors", () => {
let component = shallow(<Header />);
let wrapper = component.find(".top_bar");
expect(wrapper.length).toBe(1);
});
it("Should render without errors", () => {
let component = shallow(<Header />);
let logo = component.find(".fire_img");
expect(logo.length).toBe(1);
});
});
My component look:
class Header extends Component {
constructor() {
super();
this.state = {
time: undefined,
search: ""
};
}
componentDidMount() {
const { getData } = this.props;
getData();
}
render() {
const { getData, time } = this.props;
const { search } = this.state;
return (
<div className="top_bar">
{time ? (
<Countdown
key={time}
date={new Date(time)}
renderer={renderer}
onComplete={() => getData()}
/>
) : null}
<div>
<div className="search">
<h6>Enter value to filter products</h6>
<input
type="text"
value={search}
name="search"
autoComplete="off"
onChange={event => this.handleChange(event)}
/>
</div>
</div>
</div>
);
}
}
);
setupTest.js :
import Enzyme from "enzyme";
import Adapter from "enzyme-adapter-react-16";
Enzyme.configure({ adapter: new Adapter() });
My package.json:
"name": "interview-question",
"version": "0.1.0",
"private": true,
"devDependencies": {
"react-scripts": "^3.1.1"
},
"dependencies": {
"babel-jest": "^24.9.0",
"date-fns": "^1.28.0",
"dayjs": "^1.8.16",
"enzyme": "^3.10.0",
"enzyme-adapter-react-16": "^1.14.0",
"faker": "^4.1.0",
"jest": "^24.8.0",
"jest-enzyme": "^7.1.1",
"lodash": "^4.17.15",
"node-sass": "^4.12.0",
"react": "^16.9.0",
"react-compound-timer": "^1.1.5",
"react-countdown-now": "^2.1.1",
"react-dom": "^16.9.0",
"react-loader-spinner": "^3.1.4",
"react-redux": "^7.1.0",
"react-spinners": "^0.6.1",
"redux": "^4.0.1",
"redux-devtools-extension": "^2.13.8",
"redux-thunk": "^2.3.0",
"styled-components": "^4.3.2"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test --env=jsdom",
"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"
]
}
}
It's my first test and I don't know why test didn't work
Please help!
Thanks
Add to your package.json this config:
"jest": {
"setupFiles": [
"./path//to//your//setupTest.js"
]
}

Resources