I'm migrating our application from react 15.4 to react 16. We're using react's new errorBonudries which is awesome, but it has a major issue - events and asynchronous actions are not catched by the error boundaries, and I need to catch and log them.
The workaround I found was usign window.onerror, but looks like react "swallows" the real error details as no real data about the error is sent to the event.
Are there any suggestions for this type of handling which do not include using try/catch to every event block we're writing?
Thanks!
CodePudding user response:
You must use try/catch blocks.
CodePudding user response:
//plz check my all code and go thought my coding
//connection js
const {MongoClient} = require("mongodb");
const client = new MongoClient('mongodb://127.0.0.1:27017', {
useNewUrlParser: true,
useUnifiedTopology: true
});
client.connect(err => {
if(err){
console.error(err);
process.exit(-1);
}
console.log("Successfully connected to MongoDB");
})
module.exports = client;
//dal //product js
const product = require("./connet").db("product").collection("productdb");
const ObjectId = require("mongodb").ObjectId;
const create = async({name , price , description})=>{
const result = await product.insertOne({name, price, description});
return result.ops[0];
}
const getallproduct = async () =>{
const pro = await product.find();
return pro.toArray();
}
const getproductByID = async(id)=>{
return await product.findOne({_id:ObjectId(id)});
}
const editproduct = async(id,{name,price,description})=>{
console.log(id);
const result = await product.replaceOne({_id:ObjectId(id)},
{name, price , description});
return result.ops[0];
}
const deleteproduct = async id=>{
await product.deleteOne({_id:ObjectId(id)});
}
module.exports = {deleteproduct,editproduct,getproductByID,getallproduct,create}
//api
const {deleteproduct,editproduct,getproductByID,getallproduct,create} = require("../dal/product");
const addproduct = async ({name, price,description})=>{
const product={
name,
description,
price
}
return await create(product);
}
const getproduct = async () =>{
return await getallproduct();
}
const getproductbyid = async (id)=>{
return await getproductByID(id);
}
const deleteproduct = async id=>{
return await deleteproduct(id);
}
const update = async (id,{name,price,description}) =>{
return await editproduct(id,{name,price,description});
}
module.exports={
update,
deleteproduct,
getproduct,
addproduct,
getproductbyid
}
//routes
const Router = require("@koa/router");
const { update, deleteproduct, getproduct, addproduct, getproductbyid} = require("../api/product");
const router = new Router({
prefix:"/product"
})
router.get('/allproduct', async ctx=>{
ctx.body = await getproduct();
} )
router.get("/:id" , async ctx=>{
const id = ctx.params.id;
ctx.body = await getproductbyid(id);
})
router.post("/add" , async ctx=>{
let product = ctx.request.body;
product = await addproduct(product);
ctx.response.status(200);
ctx.body = product;
})
router.delete("/:id" , async ctx=>{
const id = ctx.params.id;
await deleteproduct(id);
ctx.response.status(200);
})
router.put("/:id", async ctx=>{
const id = ctx.params.id;
let product = ctx.request.body;
product = await update(id , product);
ctx.response.status=200;
ctx.body = product;
})
module.exports = router;
//server .js
const Koa = require("koa");
const bodyparser = require("koa-bodyparser");
const cors = require("@koa/cors");
const PORT = 8000;
const app = new Koa();
//middleware
app.use(bodyparser());
app.use(cors({
origin:["*"]
}));
//import routes
const userrouter = require("./routes/userRoutes");
//use routes
app.use(userrouter.routes());
app.use(userrouter.allowedMethods());
app.listen(PORT);
console.log(`Applicaton is running in port ${PORT}`);
//dal
//user login register
const User = require("./connet").db("users").collection("user");
const ObjectId = require("mongodb").ObjectId;
const bcrypt = require("bcrypt");
const createuser = async(data)=>{
let password = data.password;
let salt =await bcrypt.genSalt();
let hashPassword = await bcrypt.hash(password, salt);
data.password = hashPassword;
let user = await User.insertOne(data);
return user;
}
const getall = async () =>{
let users = await User.find();
return users.toArray();
}
const getbyid = async(id)=>{
let users = await User.findOne({_id:ObjectId(id)});
return users;
}
const login = async (email,password)=>{
let data = await User.findOne({"email":email});
if(data){
let pwd = await bcrypt.compare(password, data.password);
if(pwd){
return {token:data._id, userRole:data.userRole, msg:"login ok "}
}
else{
return{msg:"login faild"}
}
}
else{
return{msg:'login faild'}
}
}
module.exports={login , getbyid , getall ,createuser}
//routes
//userroutes (register/login)
const Router = require('koa-router');
const {login , getbyid , getall ,createuser} = require('../dal/User.dal');
const UserRouter = new Router({
prefix:"/users"
});
UserRouter.post("/create" , async(ctx)=>{
let data = ctx.request.body;
const alldata={
name:data?.name,
email:data?.email,
password:data?.password,
userRole:data?.userRole,
}
let newUser = await createuser(alldata);
ctx.response.status=200;
ctx.body =newUser;
})
UserRouter.get("/getall" , async(ctx)=>{
let data = await getall();
ctx.response.status=200;
ctx.body=data;
})
UserRouter.get("/:id" , async(ctx)=>{
let id = ctx.params.id;
let user = await getbyid(id);
ctx.response.status=200;
ctx.body=user;
})
UserRouter.post("/login" , async(ctx)=>{
let data = ctx.response.body;
let alldata={
email:data?.email,
password:data?.password
}
let log = await login(alldata);
ctx.response.status=200;
ctx.body=log;
})
module.exports = UserRouter;
CodePudding user response:
//frontend
//services .js
import axios from "axios"
const loginURL = "http://localhost:8000/user/login";
const createURL = "http://localhost:8000/user/create-user";
const getAllURL = "http://localhost:8000/user/get-all"
const getByIDURL = "http://localhost:8000/user/get-user/"
export async function login(data){
const alldata = {
email:data?.email,
password:data?.password
}
return axios.post(loginURL,alldata)
}
export async function CreateUser(data){
const alldata = {
name:data?.name,
email:data?.email,
password:data?.password,
userRole:data?.userRole
}
return axios.post(createURL,alldata);
}
export async function getAll(){
return axios.get(getAllURL);
}
export async function getByID(id){
return axios.get(getByIDURL id);
}
//login js
import React,{useEffect,useState} from "react";
import {useNavigate} from "react-router-dom";
import { login } from "../../services/userServices";
const Login =()=> {
const navigate = useNavigate();
const [Data, setData] = useState({
email:"",
password:""
});
const {email,password}= Data;
const onChangedata = (e)=> {
setData({...Data,[e.target.name]:e.target.value});
}
const submitdata = async (e)=> {
e.preventDefault();
try {
let data = await login(Data);
console.log("data",data);
if(data?.data?.token)
{
localStorage.setItem("token",data?.data?.token);
localStorage.setItem("userRole",data?.data?.userRole);
alert("login success");
navigate("/");
window.location.reload();
}
else
{
alert("Login failed");
}
} catch (error) {
console.log(error);
}
}
return (
<div>
<div>
<center>
<div>
<h2>Login to the system</h2>
</div>
<br /><br />
<div>
<form className="form">
<input
type="email"
placeholder="Enter your email"
name="email"
value={email}
onChange={(e)=>onChangedata(e)}
/>
<br/>
<br/>
<input
type="password"
placeholder="Enter your password"
name="password"
value={password}
onChange={(e)=>onChangedata(e)}
/>
<br/>
<br/>
<button className="btn btn-success" onClick={(e)=>submitdata(e)}>Login</button>
</form>
</div>
<br/>
<h4>Don't Have an account? Register Below</h4>
<a href="/register" className="btn btn-primary">Register</a>
</center>
</div>
</div>
)
}
module.exports = Login;
//register ,js
import React,{useEffect, useState} from "react";
import { CreateUser } from "../../services/userServices";
import { useNavigate } from "react-router-dom";
const Register = () => {
const navigate = useNavigate();
const [formdata, setformdata] = useState({
name:"",
email:"",
password:"",
userRole:""
});
const {name,email,password,userRole} = formdata;
const onChangedata = (e) =>{
setformdata({ ...formdata, [e.target.name]: e.target.value });
}
const Registeruserss = async(e)=>{
e.preventDefault();
try{
var data = await CreateUser(formdata);
console.log(data);
if(data?.data?.name){
alert("register ok");
navigate("/login");
}
else{
alert("register ok");
navigate("/");
}
}catch (err){
console.log(err)
}
}
return (
<div> <div>
<center>
<div>
<h2>Register to the System</h2>
</div>
<br /><br />
<div>
<form className="form">
<input
type="text"
placeholder="Enter your name"
name="name"
value={name}
onChange={(e)=>onChangedata(e)}
/>
<br/>
<br/>
<input
type="email"
placeholder="Enter your email"
name="email"
value={email}
onChange={(e)=>onChangedata(e)}
/>
<br/>
<br/>
<input
type="password"
placeholder="Enter your password"
name="password"
value={password}
onChange={(e)=>onChangedata(e)}
/>
<br/>
<br/>
<label>Give User Role like = (admin / student)</label>
<br/>
<input
type="text"
placeholder="Enter your userRole"
name="userRole"
value={userRole}
onChange={(e)=>onChangedata(e)}
/>
<br/>
<br/>
<button className="btn btn-success" onClick={(e)=>Registeruserss(e)}>register</button>
</form>
</div>
</center>
</div></div>
)
}
export default Register
//navbar
import React, {useEffect , useState} from "react";
import {useNavigate} from "react-router-dom";
const NavBar = ()=>{
const navigate = useNavigate();
const [userRole, setuserRole] = useState(null);
useEffect(()=>{
setuserRole(localStorage.getItem("userRole"));
},[])
const handleSubmit = (e)=>{
e.preventDefault();
localStorage.removeItem("token");
localStorage.removeItem("userRole");
navigate("/");
window.location.reload();
}
return (
<div>
<div>
<nav className="navbar navbar-expand-lg navbar-dark bg-dark">
<div className="container-fluid">
<a className="navbar-brand" href="/">Home</a>
<div className="collapse navbar-collapse" >
<div className="navbar-nav">
<a style={{ display: userRole == "admin" ? "flex" : "none" , textDecoration:"none"}} className="sidebarListItem" aria-current="page" href="/admin-pages">Admin Pages</a>
<a style={{ display: userRole == "student" ? "flex" : "none" , textDecoration:"none"}} className="sidebarListItem" href="/student-pages" aria-current="page">Student Pages</a>
</div>
</div>
</div>
<button onClick={(e)=>handleSubmit(e)} className="btn btn-primary" type="submit" style={{ float: "right", marginRight: "10px" , display:userRole ? "flex":"none"}}>
{"Logout"}
</button>
</nav>
</div>
</div>
)
}
module.exports = NavBar;
//app.js
import React , {useEffect,useState} from "react";
import {BrowserRouter as Router , Route , Routes} from "react-router-dom";
import Login from './components/Login'
import Register from './components/Register'
import Home from './components/Home'
import Navbar from './components/Navbar'
const App = () =>{
const [loggedUser, setloggedUser] = useState(null)
useEffect(() => {
setloggedUser(localStorage.getItem("token"));
}, [])
return(
<div>
<Router>
{loggedUser!== null ? <Navbar/> : <></>}
<Routes>
<Route exact path ="/" element={loggedUser !== null ? <Home/> : <Login/>}/>
<Route path ="/Register" element={<Register/>} />
<Route path ="/Home" element={<Home/>} />
</Routes>
</Router>
</div>
)
};
export default App;
//allproduct.js
import React, { useState, useEffect } from "react";
import axios from "axios";
import { Link } from "react-router-dom";
const AllProdcut = () => {
const [product, setproduct] = useState();
const [serachItem,setserachItem] =useState([]);
useEffect(async () => {
try {
const data = await (
await axios.get("http://localhost:3000/products/all")
).data;
setproduct(data);
} catch (error) {
console.log(error);
}
}, []);
function deleteProduct(_id) {
axios
.delete("http://localhost:3000/products/" _id)
.then((res) => {
console.log(res.data);
alert(" deleted");
})
.catch((err) => {
alert(err);
});
setproduct(product.filter((product) => product._id !== _id));
}
return (
<div className="container">
<br></br> <br></br> <br></br>
<Link to="/CreateProduct">
<button type="submit" className="btn btn-primary">
Add new Product
</button>
</Link>
<br></br> <br></br>
<div className="col-md-9">
<h4> Now You Can Search </h4>
<input type="search" placeholder="Search by id " aria-label="Search" onChange={event=>{setserachItem(event.target.value)}}
aria-describedby="search-addon" />
</div><br></br>
<table className="table table-dark">
<thead className="">
<tr>
<th> ID</th>
<th>name</th>
<th>price </th>
<th>Description</th>
<th>update</th>
<th>delete</th>
</tr>
</thead>
<tbody>
{product &&
product.map((product) => {
if(serachItem ==""){
return product
}else if(product.name.toLowerCase().includes(serachItem.toLowerCase())){
return product
}})
.map((product)=>{
return (
<tr>
<td>{product._id}</td>
<td>{product.name}</td>
<td>{product.description}</td>
<td>{product.price}</td>
<td>
<a
className="btn btn-warning"
href={`/products/${product._id}`} >
Update
</a>
</td>
<td>
<a
className="btn btn-warning"
onClick={() => {
deleteProduct(product._id);
}}
>
delete
</a>
</td>
</tr>
);
})}
</tbody>
</table></div>
);
}
export default AllProdcut;
//create product
import React, { useState } from "react";
import { useNavigate } from "react-router-dom";
import axios from "axios";
const CreateProduct = () => {
const [Product, setProduct] = useState({
name:'',
price:"",
description:"",
});
let navigate = useNavigate();
function sendData(e) {
e.preventDefault();
axios
.post("http://localhost:3000/products/add", Product)
.then(() => {
alert("New product Created");
navigate("/");
})
.catch((err) => {
alert(err);
});
setProduct({
name: "",
price: "",
description: "",
});
}
function handleChange(event) {
const { name, value } = event.target;
setProduct((preValue) => {
return {
...preValue,
[name]: value,
};
});
}
return (
<div className='container'>
<form onSubmit={sendData}>
<h1>Add new product</h1>
<div className="form-group row">
<label for="name" className="col-sm-3 col-form-label">
product Name
</label>
<div className="col-sm-8">
<input
type="text"
className="form-control"
id=""
name="name"
placeholder="Enter product Name"
onChange={handleChange}
value={Product.name}
/>
</div>
</div>
<div className="form-group row">
<label for="leaderITNum" className="col-sm-3 col-form-label">
price
</label>
<div className="col-sm-8">
<input
type="text"
className="form-control"
id="price"
name="price"
placeholder="Enter price"
onChange={handleChange}
value={Product.price}
required
/>
</div>
</div>
<div className="form-group row">
<label for="topicName" className="col-sm-3 col-form-label">
Product description
</label>
<div className="col-sm-8">
<input
type="text"
className="form-control"
id="description"
name="description"
placeholder="Enter description"
onChange={handleChange}
value={Product.description}
required
/>
</div>
</div>
<div className="form-group row">
<div className="col-sm-10">
<button type="submit" className="btn btn-primary">
<b >Add Product</b>
</button>
</div>
</div>
</form>
</div>
)
}
export default CreateProduct
//update product
import React, { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import axios from "axios";
import { useParams } from "react-router";
const UpdateProduct = () => {
const [Product, setProduct] = useState({
name:'',
price:"",
description:"",
});
let navigate = useNavigate();
const {id} = useParams();
useEffect(() => {
function getProduct() {
axios
.get(`http://localhost:3000/products/${id}`)
.then((res) => {
setProduct(res.data);
})
.catch((err) => {
alert(err.message);
});
}
getProduct();
}, []);
function sendData(e){
e.preventDefault();
const UpdateProduct = Product;
axios.put(`http://localhost:3000/products/${id}`,UpdateProduct)
.then(() => {
alert("updated success");
navigate("/");
})
.catch((err) => {
alert(err);
});
}
function handleChange(event) {
const { name, value } = event.target;
setProduct((preValue) => {
return {
...preValue,
[name]: value,
};
});
}
return (
<div className="container">
<br></br><br></br><br></br><br></br><br></br><br></br>
<form onSubmit={sendData}>
<h1>update product</h1>
<div className="form-group row">
<label for="name" className="col-sm-3 col-form-label">
product Name
</label>
<div className="col-sm-8">
<input
type="text"
className="form-control"
id=""
name="name"
placeholder="Enter product Name"
onChange={handleChange}
value={Product.name}
/>
</div>
</div>
<div className="form-group row">
<label for="leaderITNum" className="col-sm-3 col-form-label">
price
</label>
<div className="col-sm-8">
<input
type="text"
className="form-control"
id="price"
name="price"
placeholder="Enter price"
onChange={handleChange}
value={Product.price}
required
/>
</div>
</div>
<div className="form-group row">
<label for="topicName" className="col-sm-3 col-form-label">
Product description
</label>
<div className="col-sm-8">
<input
type="text"
className="form-control"
id="description"
name="description"
placeholder="Enter description"
onChange={handleChange}
value={Product.description}
required
/>
</div>
</div>
<div className="form-group row">
<div className="col-sm-10">
<button type="submit" className="btn btn-primary">
<b >Update</b>
</button>
</div>
</div>
</form>
</div>
)
}
export default UpdateProduct