I've been trying to get SendGrid work with my React app. I have created a config file that is emailConfig.js which I am using to send my email through my signup form in SignUp.jsx. Currently I have emailConfig in a /utlis folder I created in the client side. When I try to run my application I keep getting hit with two error messages.
Error Message 1
ERROR in ./node_modules/#sendgrid/helpers/classes/attachment.js
9:11-24
Module not found: Error: Can't resolve 'fs' in '/Users/user/Developer
Files/app/client/node_modules/#sendgrid/helpers/classes'
Error Message 2
ERROR in ./node_modules/#sendgrid/helpers/classes/attachment.js
10:13-28
Module not found: Error: Can't resolve 'path' in
'/Users/user/Developer
Files/app/client/node_modules/#sendgrid/helpers/classes'
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: { "path": require.resolve("path-browserify") }'
install 'path-browserify' If you don't want to include a polyfill, you can use an empty module like this: resolve.fallback: { "path":
false }
Should I have this in my /server/utils folder instead, the emailConfig.js and create a syslink of some sort, or what am I missing that is causing this message. I tried creating a syslink originally and couldn't get it to work.
I have gone and attached my folder structure, package.json(client), package.json(sever), SignUp.jsx, and emailConfig.js below
Folder Structure
App
/client
/src
/components
/signup
/SignUp.jsx
/utils
/emailConfig.js
/sever
package.json (client)
"name": "app",
"version": "0.1.0",
"private": true,
"dependencies": {
"#fortawesome/free-solid-svg-icons": "^6.3.0",
"#fortawesome/react-fontawesome": "^0.2.0",
"#sendgrid/mail": "^7.7.0",
"#testing-library/jest-dom": "^5.16.5",
"#testing-library/react": "^13.4.0",
"#testing-library/user-event": "^13.5.0",
"axios": "^1.3.3",
"emailjs-com": "^3.2.0",
"formik": "^2.2.9",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-router-dom": "^6.8.1",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4",
"yup": "^1.0.0"
},
"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"
]
}
}
package.json (server)
{
"name": "app-server",
"version": "1.0.0",
"description": "backhend of kinkbucket",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node app.js",
"build": "react-scripts build",
"eject": "react-scripts eject"
},
"author": "Ainsley",
"license": "ISC",
"dependencies": {
"cors": "^2.8.5",
"dotenv": "^16.0.3",
"express": "^4.18.2",
"mongoose": "^6.9.2"
},
"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"
]
}
}
SignUp.jsx
import React, { useState } from "react";
import { useFormik } from "formik";
import * as Yup from "yup";
import { FontAwesomeIcon } from "#fortawesome/react-fontawesome";
import { faEye, faEyeSlash } from "#fortawesome/free-solid-svg-icons";
import axios from "axios";
import { useNavigate } from "react-router-dom";
import emailjs from "emailjs-com";
import emailConfig from "../../utils/emailConfig.js";
import "./signUp.css";
const validationSchema = Yup.object().shape({
username: Yup.string().required("Required"),
email: Yup.string().email("Invalid email").required("Required"),
password: Yup.string().required("Required"),
confirmPassword: Yup.string().oneOf(
[Yup.ref("password"), null],
"Passwords must match"
),
});
const SignUp = () => {
const [showPassword, setShowPassword] = useState(false);
const history = useNavigate();
const formik = useFormik({
initialValues: {
username: "",
email: "",
password: "",
confirmPassword: "",
},
validationSchema,
onSubmit: async (values) => {
try {
const response = await axios.post("/api/users/signup", values);
const userId = response.data._id;
const token = response.data.token;
// Send verification email
emailjs
.send(
emailConfig.SERVICE_ID,
emailConfig.TEMPLATE_ID,
{
to_name: values.username,
message: `Please click this link to verify your email address: https://YOUR_DOMAIN/verify/${userId}/${token}`,
to_email: values.email,
},
emailConfig.USER_ID
)
.then(
(result) => {
console.log(result.text);
},
(error) => {
console.log(error.text);
}
);
history.push("/");
} catch (err) {
console.log(err);
}
},
});
const { values, errors, touched, handleChange, handleBlur, handleSubmit } =
formik;
const handleSignUp = (e) => {
e.preventDefault();
handleSubmit();
};
return (
<div className="signup-container">
<form onSubmit={handleSubmit} className="signup-form">
<h2>Sign Up</h2>
<div className="form-control">
<label htmlFor="username">Username</label>
<input
type="text"
id="username"
name="username"
value={values.username}
onChange={handleChange}
onBlur={handleBlur}
/>
{touched.username && errors.username && (
<div className="error">{errors.username}</div>
)}
</div>
<div className="form-control">
<label htmlFor="email">Email</label>
<input
type="email"
id="email"
name="email"
value={values.email}
onChange={handleChange}
onBlur={handleBlur}
/>
{touched.email && errors.email && (
<div className="error">{errors.email}</div>
)}
</div>
<div className="form-control password-input">
<label htmlFor="password">Password</label>
<input
type={showPassword ? "text" : "password"}
id="password"
name="password"
value={values.password}
onChange={handleChange}
onBlur={handleBlur}
/>
<button
type="button"
className="toggle-password"
onClick={() => setShowPassword(!showPassword)}
>
<FontAwesomeIcon icon={showPassword ? faEyeSlash : faEye} />
</button>
{touched.password && errors.password && (
<div className="error">{errors.password}</div>
)}
</div>
<div className="form-control">
<label htmlFor="confirmPassword">Confirm Password</label>
<input
type="password"
id="confirmPassword"
name="confirmPassword"
value={values.confirmPassword}
onChange={handleChange}
onBlur={handleBlur}
/>
{touched.confirmPassword && errors.confirmPassword && (
<div className="error">{errors.confirmPassword}</div>
)}
</div>
<div className="form-control">
<input type="checkbox" id="terms" name="terms" />
<label htmlFor="terms">I agree to the terms and conditions</label>
</div>
<div className="form-actions">
<button
type="submit"
className="signup-button"
disabled={!formik.isValid}
onClick={handleSignUp}
>
Sign Up
</button>
</div>
</form>
</div>
);
};
export default SignUp;
emailConfig.js
const sgMail = require("#sendgrid/mail");
sgMail.setApiKey(process.env.SENDGRID_API_KEY);
const sendConfirmationEmail = (to, name) => {
const msg = {
to,
from: "your_email#example.com",
subject: "Welcome to KinkBucket!",
text: `Hi ${name}, thanks for signing up with KinkBucket!`,
html: `<p>Hi ${name},<br><br>Thanks for signing up with KinkBucket!</p>`,
};
sgMail.send(msg);
};
module.exports = { sendConfirmationEmail };
Related
I first take my time to thank you for reading this. I am desperately in need of your help. I know there are many questions out there that are similar to this and have been answered but I tried my best to follow them all. Nothing worked, so I would like a direct answer to my problem via this post. Refer to this and you will know what I'm talking about: https://youtu.be/FX5HE_gnOTI
I have a couple problems that may be related to one and another. So I followed mostly what the guy in the video did but there is a problem in my work that says otherwise: When I hit the VIEW button, the information submitted doesn't populate. When I hit the DELETE button, it does not delete the item. (I have to manually send a request via Postman Agent and refresh the browser to see it delete.) And when I hit the EDIT button, it would not save and go back the main page when I hit SAVE. I have spent hours researching and debugging but none of them worked. Your help will be much appreciated and a huge thank you (I deeply mean it), if you managed to help me fix it.
The console of my application.
import React, { Component } from 'react'
import StudentService from '../services/StudentService';
class UpdateStudentComponent extends Component {
constructor(props) {
super(props)
this.state = {
id: this.props.match.params.id,
firstName: '',
lastName: '',
emailId: ''
}
this.changeFirstName = this.changeFirstName.bind(this);
this.changeLastName = this.changeLastName.bind(this);
this.changeEmail = this.changeEmail.bind(this);
this.updateStudent = this.updateStudent.bind(this);
}
componentDidMount() {
StudentService.getStudentId(this.state.id).then((res) => {
let student = res.data;
this.setState
({firstName: student.firstName,
lastName: student.lastName,
emailId: student.emailId
});
});
}
updateStudent = (e) => {
e.preventDefault();
let student = {firstName: this.state.firstName, lastName: this.state.lastName, emailId: this.state.emailId};
console.log('student => ' + JSON.stringify(student));
console.log('id => ' + JSON.stringify(this.state.id));
StudentService.updateStudent(student, this.state.id).then(res => {
this.props.history.push('/students');
});
}
changeFirstName = (event) => {
this.setState({firstName: event.target.value});
}
changeLastName = (event) => {
this.setState({lastName: event.target.value});
}
changeEmail = (event) => {
this.setState({emailId: event.target.value});
}
cancel() {
this.props.history.push('/students');
}
render() {
return (
<div>
<br></br>
<div className = "container">
<div className = "row">
<div className = "card col-md-6 offset-md-3 offset-md-3">
<h3 className="text-center">Update Student</h3>
<div className = "card-body">
<form>
<div className = "form-group">
<label> First Name: </label>
<input placeholder="First Name" name="firstName" className="form-control"
value={this.state.firstName} onChange={this.changeFirstName}/>
</div>
<div className = "form-group">
<label> Last Name: </label>
<input placeholder="Last Name" name="lastName" className="form-control"
value={this.state.lastName} onChange={this.changeLastName}/>
</div>
<div className = "form-group">
<label> Email Id: </label>
<input placeholder="Email Address" name="emailId" className="form-control"
value={this.state.emailId} onChange={this.changeEmail}/>
</div>
<button className="btn btn-success" onClick={this.updateStudent}> Save </button>
<button className="btn btn-danger" onClick={this.cancel.bind(this)} style={{marginLeft: "10px"}}> Cancel </button>
</form>
</div>
</div>
</div>
</div>
</div>
)
}
}
export default UpdateStudentComponent
import React, { Component } from 'react'
import StudentService from '../services/StudentService'
class ListStudentComponent extends Component {
constructor(props) {
super(props)
this.state = {
students: []
}
this.addStudent = this.addStudent.bind(this);
this.editStudent = this.editStudent.bind(this);
this.deleteStudent = this.deleteStudent.bind(this);
}
deleteStudent(id) {
StudentService.deleteStudent(id).then(res => {
this.setState({students: this.state.students.filter(student => student.id !== id)});
}).catch(error => console.log(error));
}
viewStudent(id){
this.props.history.push(`/view-student/${id}`);
}
editStudent(id){
this.props.history.push(`/add-student/${id}`);
}
componentDidMount(){
StudentService.getStudents().then((res) => {
this.setState({students: res.data});
});
}
addStudent(){
this.props.history.push('/add-student/_add');
}
render() {
return (
<div>
<h2 className="text-center">Students List</h2>
<div className = "row">
<button className="btn btn-primary" onClick={this.addStudent}> Add Student </button>
</div>
<br></br>
<div className = "row">
<table className = "table table-striped table-bordered">
<thead>
<tr>
<th> Student First Name</th>
<th> Student Last Name</th>
<th> Student Email Id</th>
<th> Actions</th>
</tr>
</thead>
<tbody>
{
this.state.students.map(
student =>
<tr key = {student.id}>
<td> {student.firstName} </td>
<td> {student.lastName}</td>
<td> {student.emailId}</td>
<td>
<button onClick={ () => this.editStudent(student.id)} className="btn btn-success"> Edit </button>
<button style={{marginLeft: "10px"}} onClick={ () => this.deleteStudent(student.id)} className="btn btn-danger"> Delete </button>
<button style={{marginLeft: "10px"}} onClick={ () => this.viewStudent(student.id)} className="btn btn-info"> View </button>
</td>
</tr>
)
}
</tbody>
</table>
</div>
</div>
)
}
}
export default ListStudentComponent
import React, { Component } from 'react'
import StudentService from '../services/StudentService'
class ViewStudentComponent extends Component {
constructor(props) {
super(props)
this.state = {
id: this.props.match.params.id,
student: []
}
}
componentDidMount() {
StudentService.getStudentById(this.state.id).then(res => {
this.setState({student: res.data});
})
}
render() {
return (
<div>
<br></br>
<div className = "card col-md-6 offset-md-3">
<h3 className = "text-center"> View Student Details </h3>
<div className = "card-body">
<div className = "row">
<label> Student First Name: </label>
<div> {this.state.student.firstName} </div>
</div>
<div className = "row">
<label> Student Last Name: </label>
<div> {this.state.student.lastName} </div>
</div>
<div className = "row">
<label> Student Email ID: </label>
<div> {this.state.student.emailId} </div>
</div>
</div>
</div>
</div>
)
}
}
export default ViewStudentComponent
import axios from 'axios';
const STUDENT_API_BASE_URL = "http://localhost:8080/api/v1/students";
class StudentService {
getStudents() {
return axios.get(STUDENT_API_BASE_URL);
}
createStudent(student) {
return axios.post(STUDENT_API_BASE_URL, student);
}
getStudentById(studentId) {
return axios.get(STUDENT_API_BASE_URL + '/' + studentId);
}
updateStudent(student, studentId) {
return axios.put(STUDENT_API_BASE_URL + '/' + studentId, student);
}
deleteStudent(studentId) {
return axios.delete(STUDENT_API_BASE_URL + '/' + studentId);
}
}
export default new StudentService()
package com.studentroster.springboot.controller;
import java.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import com.studentroster.springboot.exception.ResourceNotFoundException;
import com.studentroster.springboot.model.Students;
import com.studentroster.springboot.repository.StudentRepository;
#CrossOrigin(origins = "http://localhost:3000")
#RestController
#RequestMapping("/api/v1/")
public class StudentController {
#Autowired
private StudentRepository stud_rep;
// GET all students
#GetMapping("/students")
public List<Students> getAllStudents() {
return stud_rep.findAll();
}
// ADD student
#PostMapping("/students")
public Students addStudent(#RequestBody Students student) {
return stud_rep.save(student);
}
// Get Student ID
#GetMapping("/students/{id}")
public ResponseEntity<Students> getStudentId(#PathVariable Long id) {
Students stud = stud_rep.findById(id).orElseThrow(() -> new ResourceNotFoundException("Student does not exist with the id: " + id));
return ResponseEntity.ok(stud);
}
// UPDATE student
#PutMapping("/students/{id}")
public ResponseEntity<Students> updateStudent(#PathVariable Long id, #RequestBody Students studentDetails) {
Students stud = stud_rep.findById(id).orElseThrow(() -> new ResourceNotFoundException("Student does not exist with the id: " + id));
stud.setFirstName(studentDetails.getFirstName());
stud.setLastName(studentDetails.getLastName());
stud.setEmail(studentDetails.getEmail());
Students studentUpdated = stud_rep.save(stud);
return ResponseEntity.ok(studentUpdated);
}
// DELETE student
#DeleteMapping("/students/{id}")
public ResponseEntity<Map<String, Boolean>> deleteStudent(#PathVariable Long id) {
Students stud = stud_rep.findById(id).orElseThrow(() -> new ResourceNotFoundException("Student does not exist with the id: " + id));
stud_rep.delete(stud);
Map<String, Boolean> response = new HashMap<>();
response.put("Deleted", Boolean.TRUE);
return ResponseEntity.ok(response);
}
}
{
"name": "react-frontend",
"version": "0.1.0",
"private": true,
"dependencies": {
"#testing-library/jest-dom": "^4.2.4",
"#testing-library/react": "^9.5.0",
"#testing-library/user-event": "^7.2.1",
"axios": "^0.19.2",
"bootstrap": "^4.5.0",
"react": "^16.13.1",
"react-dom": "^16.13.1",
"react-router-dom": "^5.2.0",
"react-scripts": "^3.4.1"
},
"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"
]
}
}
import React from 'react';
import logo from './logo.svg';
import './App.css';
import {BrowserRouter as Router, Route, Switch} from 'react-router-dom'
import ListStudentComponent from './components/ListStudentComponent';
import HeaderComponent from './components/HeaderComponent';
import FooterComponent from './components/FooterComponent';
import CreateStudentComponent from './components/CreateStudentComponent';
import UpdateStudentComponent from './components/UpdateStudentComponent';
import ViewStudentComponent from './components/ViewStudentComponent';
function App() {
return (
<div>
<Router>
<HeaderComponent />
<div className="container">
<Switch>
<Route path = "/" exact component = {ListStudentComponent}></Route>
<Route path = "/students" component = {ListStudentComponent}></Route>
<Route path = "/add-student/:id" component = {CreateStudentComponent}></Route>
<Route path = "/view-student/:id" component = {ViewStudentComponent}></Route>
<Route path = "/update-student/:id" component = {UpdateStudentComponent}></Route>
</Switch>
</div>
<FooterComponent />
</Router>
</div>
);
}
export default App;
I have posted all the necessary files. Please let me know if you have any further questions and I thank you from the bottom of my heart if you manage to fix my problem.
I just migrated to react-flow-renderer version 10 about 5 hours back (it launched around 10 hours ago). I am trying to arrange nodes on a graph with the help of dagre library for layouting & Vite js as a build tool
However, I keep getting thrown the error - Uncaught SyntaxError: The requested module '/node_modules/.vite/react-flow-renderer.js?v=6f1c077c' does not provide an export named 'useEdgesState'
Here's a screenshot of my codebase & my package.json (where I'm using react-flow-renderer v10.0.2)
import React, { useCallback } from 'react';
import ReactFlow, { addEdge, useNodesState, useEdgesState, Edge, Node, Position, ConnectionLineType } from 'react-flow-renderer';
import dagre from 'dagre';
import { initialNodes, initialEdges } from '../../../nodes-edges';
import './layouting.css';
const dagreGraph = new dagre.graphlib.Graph();
dagreGraph.setDefaultEdgeLabel(() => ({}));
const nodeWidth = 172;
const nodeHeight = 36;
const getLayoutedElements = (nodes:Node[], edges:Edge[], direction = 'TB') => {
const isHorizontal = direction === 'LR';
dagreGraph.setGraph({ rankdir: direction });
nodes.forEach((node:Node) => {
dagreGraph.setNode(node.id, { width: nodeWidth, height: nodeHeight });
});
edges.forEach((edge:Edge) => {
dagreGraph.setEdge(edge.source, edge.target);
});
dagre.layout(dagreGraph);
nodes.forEach((node) => {
const nodeWithPosition = dagreGraph.node(node.id);
node.targetPosition = isHorizontal ? Position.Left : Position.Top;
node.sourcePosition = isHorizontal ? Position.Right : Position.Bottom;
// We are shifting the dagre node position (anchor=center center) to the top left
// so it matches the React Flow node anchor point (top left).
node.position = {
x: nodeWithPosition.x - nodeWidth / 2,
y: nodeWithPosition.y - nodeHeight / 2,
};
return node;
});
return { nodes, edges };
};
const { nodes: layoutedNodes, edges: layoutedEdges } = getLayoutedElements(
initialNodes,
initialEdges
);
const LayoutFlow = () => {
const [nodes, setNodes, onNodesChange] = useNodesState(layoutedNodes);
const [edges, setEdges, onEdgesChange] = useEdgesState(layoutedEdges);
const onConnect = useCallback(
(params) => setEdges((eds) => addEdge({ ...params, type: 'smoothstep', animated: true }, eds)),
[]
);
const onLayout = useCallback(
(direction) => {
const { nodes: layoutedNodes, edges: layoutedEdges } = getLayoutedElements(
nodes,
edges,
direction
);
setNodes([...layoutedNodes]);
setEdges([...layoutedEdges]);
},
[nodes, edges]
);
return (
<div className="layoutflow">
<ReactFlow
nodes={nodes}
edges={edges}
onNodesChange={onNodesChange}
onEdgesChange={onEdgesChange}
onConnect={onConnect}
connectionLineType={ConnectionLineType.SmoothStep}
fitView
/>
<div className="controls">
<button onClick={() => onLayout('TB')}>vertical layout</button>
<button onClick={() => onLayout('LR')}>horizontal layout</button>
</div>
</div>
);
};
export default LayoutFlow;
{
"name": "app-frontend",
"private": true,
"version": "0.0.0",
"scripts": {
"dev": "vite",
"build": "tsc && vite build",
"preview": "vite preview"
},
"dependencies": {
"#ant-design/icons": "^4.7.0",
"antd": "^4.19.2",
"dagre": "^0.8.5",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-flow-renderer": "^10.0.2"
},
"devDependencies": {
"#types/d3": "^7.1.0",
"#types/dagre": "^0.7.47",
"#types/react": "^17.0.33",
"#types/react-dom": "^17.0.10",
"#vitejs/plugin-react": "^1.0.7",
"eslint": "^8.11.0",
"husky": "^7.0.4",
"lint-staged": "^12.3.5",
"prettier": "^2.5.1",
"typescript": "^4.5.4",
"vite": "^2.8.0"
}
}
The docs I referred to, to achieve this are here - https://reactflow.dev/docs/examples/layouting/
Can someone please help debug this ? I have a feeling, Vite's module bundling is causing this error
I have a full-stack React.js application deployed on Heroku. Everything deployed fine except for Mapbox. In development, everything works nice. As soon as I open my application in Heroku, Mapbox displays a black screen.
I have added config vars in Heroku for the default public Mapbox token.
When I check the console in production, I am getting an error saying "Uncaught ReferenceError: y is not defined"
I'm using Mapbox with React Map GL, and not sure what the issue is, looking for help at this point.
I have added a screenshot of how it looks in development and the black screen I get in production.production-mapbox-error development-mapbox-working
my client-side package.json:
"name": "client",
"version": "0.1.0",
"private": true,
"dependencies": {
"#testing-library/jest-dom": "^5.11.8",
"#testing-library/react": "^11.2.2",
"#testing-library/user-event": "^12.6.0",
"framer-motion": "^3.2.1",
"node-sass": "^4.14.1",
"react": "^17.0.1",
"react-dom": "^17.0.1",
"react-hook-form": "^6.14.1",
"react-map-gl": "^6.0.2",
"react-router-dom": "^5.2.0",
"react-scripts": "4.0.1",
"web-vitals": "^0.2.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:8080"
}
my ReactMapGL component:
import ReactMapGL, { Marker, Popup } from "react-map-gl";
import { listLogEntries } from "./api";
import MapPin from "../../assets/icons/map-pin1.svg";
import MapPinRed from "../../assets/icons/map-pin-red1.svg";
import LogEntryForm from "../LogEntryForm/logEntryForm";
import "./reactMap.scss";
const ReactMap = () => {
const [logEntries, setLogEntries] = useState([]);
const [showPopup, setShowPopup] = useState({});
const [addEntryLocation, setAddEntryLocation] = useState(null);
const [viewport, setViewport] = useState({
width: "100vw",
height: "100vh",
latitude: 49.246292,
longitude: -123.116226,
zoom: 8,
});
const getEntries = async () => {
const logEntries = await listLogEntries();
setLogEntries(logEntries);
};
useEffect(() => {
getEntries();
}, []);
const showAddMarkerPopup = (event) => {
const [longitude, latitude] = event.lngLat;
setAddEntryLocation({
longitude,
latitude,
});
};
const MAP = process.env.REACT_APP_MAPBOX_TOKEN;
const MAP_STYLE = process.env.REACT_APP_MAP_STYLE;
return (
<div className="map">
<ReactMapGL
className="map__react-gl"
{...viewport}
// Setting map theme from mapbox
mapStyle={MAP_STYLE}
// mapbox Api Access Token
mapboxApiAccessToken={MAP}
onViewportChange={setViewport}
onDblClick={showAddMarkerPopup}
>
{logEntries.map((entry) => (
<div key={entry._id}>
<Marker latitude={entry.latitude} longitude={entry.longitude}>
<div
onClick={() =>
setShowPopup({
[entry._id]: true,
})
}
>
<img
className="map__pin"
style={{
width: `${4 * viewport.zoom}px`,
height: `${4 * viewport.zoom}px`,
}}
src={MapPin}
alt="Map Pin"
/>
</div>
</Marker>
{showPopup[entry._id] ? (
<Popup
className="map__popup"
latitude={entry.latitude}
longitude={entry.longitude}
dynamicPosition={true}
closeButton={true}
closeOnClick={false}
onClose={() => setShowPopup({})}
anchor="top"
>
<div className="map__info-container">
<h3 className="map__info-heading">{entry.title}</h3>
<hr className="map__hr" />
<p className="map__info-description">{entry.description}</p>
<hr className="map__hr" />
<p className="map__info-comment">{entry.comments}</p>
<div className="map__info-image-container">
{entry.image && (
<img
className="map__image"
src={entry.image}
alt={entry.title}
/>
)}
</div>
<small className="map__info-visited">
Visited on: {new Date(entry.visitDate).toLocaleDateString()}
</small>
</div>
</Popup>
) : null}
</div>
))}
{addEntryLocation ? (
<div>
<Marker
latitude={addEntryLocation.latitude}
longitude={addEntryLocation.longitude}
>
<div>
<img
className="map__pin-red"
style={{
width: `${4 * viewport.zoom}px`,
height: `${4 * viewport.zoom}px`,
}}
src={MapPinRed}
alt="Map Pin"
/>
</div>
</Marker>
<Popup
className="map__popup"
latitude={addEntryLocation.latitude}
longitude={addEntryLocation.longitude}
dynamicPosition={true}
closeButton={true}
closeOnClick={false}
onClose={() => setAddEntryLocation(null)}
anchor="top"
>
<div className="map__new-info-container">
<LogEntryForm
onClose={() => {
setAddEntryLocation(null);
getEntries();
}}
location={addEntryLocation}
/>
<form action=""></form>
</div>
</Popup>
</div>
) : null}
</ReactMapGL>
</div>
);
};
export default ReactMap;
This is an issue of Webpack. For any future viewers, here's what worked for me:
import ReactMapGL, {Marker} from 'react-map-gl'
import 'mapbox-gl/dist/mapbox-gl.css';
import mapboxgl from 'mapbox-gl';
// eslint-disable-next-line import/no-webpack-loader-syntax
mapboxgl.workerClass = require('worker-loader!mapbox-gl/dist/mapbox-gl-csp-worker').default;
Also, remember to npm install worker-loader.
So after some more research, I found that the problem is in the version of react-map-gl (6.0.2). Installing react-map-gl#5.2.5 finally displayed my Layers and everything works fine. I don't know what is the problem in version 6.0.2. Hope they will fix this soon.
I'm trying to add a page in my NextJS project which contains a form for posting some information. This page is only accessible by clicking an "add new" bootstrap button, wrapped in a Link tag. The redirect goes fine but when I click on the browser's back button it takes like 2 min to go back to the homepage (where is the "add new" button).
this is my Package.json:
{
"name": "FrontEnd",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"dev": "next",
"build": "next build",
"start": "next start"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"#zeit/next-css": "^1.0.1",
"bootstrap": "^4.3.1",
"isomorphic-unfetch": "^3.0.0",
"next": "^9.1.1",
"react": "^16.10.2",
"react-calendar": "^2.19.2",
"react-dom": "^16.10.2"
}
}
My 'Home' page:
const Index = (props) => (
<Layout>
<ul>
{props.reservas.map(reserva => (
<li>
<ReservaPreview props={reserva.props}/>
</li>
))}
<li><AgregarReservaBoton /></li>
</ul>
</Layout>
);
My 'Bootstrap button':
class AgregarReservaBoton extends Component {
render() {
return (
<div>
<Link href='/nuevaReserva'>
<button type="button"></button>
</Link>
</div>
)
}
}
My 'Redirect' page:
const NuevaReserva = (props) => (
<div>
<Layout>
<AgregarReservaForm />
</Layout>
</div>
)
Imports and Exports done.
Browser's back button working fine.
I have this app with updated node_modules where Signup fails but everything else works. i have a backup of old version of node_modules when i replace the current version with that one. it starts to work. I am also deploying it on netlify. So when i run npm run build and upload the build folder manually to netlify it works, but when i try deploying from github, signup fails again.
I tried replacing the package.json with the old one, then running npm install but that doesn't work either.
Code for signup
import { Link, withRouter } from "react-router-dom";
import { Redirect } from "react-router";
import PasswordMask from "react-password-mask";
import {
withFirebase,
firebase,
FirebaseContext,
db
} from "../../../Components/Firebase/firebase";
import * as ROUTES from "../../../Constants/routes";
import { compose } from "recompose";
import PhyxData from "../../../Constants/phyxData.js";
import "./styles.css";
const DemoSignUpPage = () => (
<div>
<img
src="/images/demoOnePage/group.png"
className="demo-page-one-illustration dp-signup"
/>
<div
className="lead-text margin-top-40 demo-signup"
>
Thanks for trying Phyxable!
<br />
Let's continue the healing process.
</div>
<div className="center margin-top-16">
<div className="inline-block">
<DemoSignUpForm />
</div>
</div>
</div>
);
const INITIAL_STATE = {
username: "",
email: "",
passwordOne: "",
passwordTwo: "",
error: null
};
class DemoSignUpFormBase extends Component {
constructor(props) {
super(props);
this.state = { ...INITIAL_STATE, redirect: false };
}
onSubmit = event => {
console.log("sign up submit called", this.props);
const { username, email, passwordOne } = this.state;
this.props.firebase
.doCreateUserWithEmailAndPassword(email, passwordOne)
.then(authUser => {
console.log("sign up submit called 2");
return this.props.firebase.user(authUser.uid).update({
joinDate: new Date().toLocaleDateString("en-US"),
userProfile: {
lastPhyx: { date: new Date(), level: 1, session: 1 },
subscription: { paid: false },
progress: {
posture: {
1: { 0: { date: new Date().toLocaleDateString("en-US") } }
}
},
name: username,
email: email,
score: {
feelingGood: 1,
lastDate: new Date().toLocaleDateString("en-US"),
longestStreak: 1,
streak: 1,
totalTime: 2
},
VAS: {},
currentPhyx: "posture",
accountType: "USER",
notification: {},
signedIn: false
}
});
})
.then(authUser => {
console.log("in on submit sign up");
this.setState({ ...INITIAL_STATE });
this.setState({ redirect: true });
})
.catch(error => {
this.setState({ error });
});
event.preventDefault();
};
onChange = event => {
this.setState({ [event.target.name]: event.target.value });
};
handleTryFirstClick = () => {
this.setState({ redirect: true });
};
render() {
console.log("demo sign up", this.props);
if (this.state.redirect) {
// return <Redirect push to="/home" />;
window.location.href = "/home";
}
const { username, email, passwordOne, passwordTwo, error } = this.state;
const isInvalid =
// passwordOne !== passwordTwo ||
passwordOne === "" || email === "" || username === "";
return (
<form className="margin-top-16">
<div className="center">
<div className="inline-block">
<input
name="username"
value={username}
onChange={this.onChange}
type="text"
placeholder="Full Name"
/>
<div className="height-8" />
<input
name="email"
value={email}
onChange={this.onChange}
type="text"
placeholder="Email Address"
/>
<div className="height-8" />
<PasswordMask
id="password"
name="passwordOne"
value={passwordOne}
onChange={this.onChange}
type="password"
placeholder="Password"
inputStyles={{
padding: "8px",
fontSize: "16px"
}}
inputClassName="PasswordMaskInput"
buttonStyles={{
width: "61px"
}}
/>
{/* <PasswordMask
name="passwordTwo"
value={passwordTwo}
onChange={this.onChange}
type="password"
placeholder="Confirm Password"
inputStyles={{
padding: "8px",
fontSize: "16px"
}}
inputClassName="PasswordMaskInput"
buttonStyles={{
width: "61px"
}}
/> */}
</div>
</div>
<div className="margin-top-40">
<button
onClick={event => {
this.onSubmit(event);
}}
disabled={isInvalid}
type="submit"
>
Sign Up
</button>
</div>
{error && <p>{error.message}</p>}
</form>
);
}
}
const DemoSignUpForm = compose(
withRouter,
withFirebase
)(DemoSignUpFormBase);
export default DemoSignUpPage;
export { DemoSignUpForm };
Here is my package.json :
{
"name": "finalphyx",
"version": "0.1.0",
"private": true,
"dependencies": {
"#material-ui/lab": "^3.0.0-alpha.30",
"disable-scroll": "^0.4.1",
"firebase": "^6.1.1",
"firebase-functions": "^2.3.1",
"html-loader": "^0.5.5",
"mdbreact": "^4.15.0",
"netlify": "^2.4.6",
"react": "^16.7.0",
"react-bootstrap": "^0.32.4",
"react-div-100vh": "^0.3.4",
"react-dom": "^16.7.0",
"react-firebaseui": "^3.1.2",
"react-ga": "^2.5.7",
"react-jw-player": "^1.19.0",
"react-meta-tags": "^0.7.4",
"react-password-mask": "^3.3.1",
"react-player": "^1.11.0",
"react-responsive": "^7.0.0",
"react-router-dom": "^5.0.1",
"react-scripts": "^3.0.1",
"react-scroll": "^1.7.11",
"react-share": "^3.0.0",
"react-stripe-checkout": "^2.6.3",
"react-stripe-elements": "^3.0.0",
"react-sweet-progress": "^1.1.2",
"recompose": "^0.30.0",
"stripe": "^7.1.0",
"video-react": "^0.13.7",
"waypoints": "^4.0.1",
"window-scroll-manager": "^1.1.4"
},
"devDependencies": {
"bundle-loader": "^0.5.6",
"prettier": "^1.18.2",
"pretty-quick": "^1.11.0",
"aws-sdk": "^2.1.1"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build && echo '/* /index.html 200' > build/_redirects",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject",
"deploy": "aws s3 sync build s3://www.phyxable.com"
},
"main": "index.js",
"repository": {
"type": "git",
"url": "git+https://jacobmjones#bitbucket.org/jacobmjones/web.git"
},
"browserslist": [
">0.2%",
"not dead",
"not ie <= 11",
"not op_mini all"
],
"homepage": "/",
"author": "",
"license": "ISC",
"description": ""
}
If the problem as exactly as you described, then it is obviously not a problem with your code but with your dependencies. Notice that it is also natural that if your code works with certain versions it might not work with others (whether upgraded or downgraded)
The first thing i would try is get the old package json, and run a clear install with it (clear your node cache and completely delete your node_modules folder, after you backed up what you need to do). If it works cool, if not, then one of your dependencies has a change that was meant to be minor but yet was a breaking change (it caused your code to stop working)
Now usually because new versions (even ones that were not meant to have breaking changes) can cause breaking changes, npm creates a file that is called package-lock.json. Unlike the package.json this one contains the exact versions that was used during a certain installation, and installing node modules using this package file, should exactly mirror the state of your dependencies at that time.
If you have that lock file and install with it -using npm ci- then it should work.