Home > Software engineering >  how to use try catch react
how to use try catch react

Time:06-27

import React, { Component } from "react";
import NavBar from "./components/NavBar";
import Counters from "./components/counters";
import "./App.css";
import ErrorBoundary from "./components/ErrorBoundary";
const lodash = require("lodash");
let uniqid = require("uniqid");
class App extends Component {
  state = {
    counters: [
      { id: uniqid(), value: 0 },
      { id: uniqid(), value: 0 },
      { id: uniqid(), value: 0 },
      { id: uniqid(), value: 0 }
    ]
  };
  constructor(props) {
    super(props);
    this.initialCounters = lodash.cloneDeep(this.state.counters);
  }
  handleDefault = () => {
    const counters = this.initialCounters;
    this.setState({ counters });
  };

  handleIncrement = counter => {
    const counters = [...this.state.counters];
    const index = counters.indexOf(counter);
    counters[index] = { ...counter };
    counters[index].value  ;
    this.setState({ counters });
  };
  handleAddition = counter => {
    // console.log("Adding new components");
    const counters = [...this.state.counters];
    console.log(counters);
    // console.log("The old length is: ", counters.length);
    const index = counters.length;
    counters[index] = { ...counter };
    // console.log("The new length is: ", counters.length);
    counters[index].value = 0;
    counters[index].id = uniqid();
    // console.log("The ID is", counters[index].id);
    this.setState({ counters });
  };
  handleDelete = counterId => {
    console.log("Event Handler Called", counterId);
    const counters = this.state.counters.filter(c => c.id !== counterId);
    this.setState({ counters });
  };

  handleReset = () => {
    const counters = this.state.counters.map(c => {
      c.value = 0;
      return c;
    });
    this.setState({ counters });
  };
  render() {
    if (this.state.counters.length === 0) {
      return (
        <React.Fragment>
          <h1>All Items have been deleted.</h1>
          <p>Click on default to get back to default state</p>
          <button
            onClick={this.handleDefault}
            className="btn btn-primary btn-sm m-2"
          >
            Default
          </button>
        </React.Fragment>
      );
    }
    return (
      <React.Fragment>
        <ErrorBoundary>
          <NavBar
            totalValues={this.state.counters
              .map(c => c.value)
              .reduce(function(acc, curr) {
                return acc   curr;
              })}
          />
        </ErrorBoundary>
        <ErrorBoundary>
          <Counters
            counters={this.state.counters}
            onDefault={this.handleDefault}
            onReset={this.handleReset}
            onIncrement={this.handleIncrement}
            onDelete={this.handleDelete}
            onAdd={this.handleAddition}
          />
        </ErrorBoundary>
      </React.Fragment>
    );
  }
}

export default App;

i am trying to learn error handling in react. The application is live here and GitHub code is this. I am trying to get a fallback UI when error rises in Navbar(navbar.jsx) the way which is mentioned in React documentation, but, I am not able to implement it the way I want to.In App.js, when I render only one return() and get navbar component into errorBoundary, I am not getting the required fallback UI.

CodePudding user response:

try {
  console.log(window.device.version)
} catch (e : TypeError) {
  console.log('Error')
}

CodePudding user response:

//all display product

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}`} >
                                        &nbsp;&nbsp; Update
                      </a>

                                </td>

                                <td>
                                    <a
                                        className="btn btn-warning"
                                        onClick={() => {
                                          
                                            deleteProduct(product._id);
                                        }}
                                    >
                      
                                        &nbsp;&nbsp; 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

CodePudding user response:

//update 

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

CodePudding user response:

//login
import React , {useEffect , useState}from 'react'
import { useNavigate } from "react-router-dom";
import {loginfuntion } from "../services/Auth";

const Login = () => {

    const navigate = useNavigate();

    const [formdata ,setformdata] = useState({
        email:"",
        password:""
    });

    const {email,password} = formdata;
    const onChangedata = (e) =>{

        setformdata({ ...formdata, [e.target.name]: e.target.value });
    }

    const submitdata = async (e)=>{
        e.preventDefault();
        console.log("data" ,formdata);
        let data = await loginfuntion(formdata);
        console.log("data", data);
        if(data?.data?.token)
        {
            localStorage.setItem("token" , data?.data?.token);
            localStorage.setItem("userRole" , data?.data?.userRole);
            navigate("/");
            window.location.reload();
        }
        else{
            alert("login fail");
        }
    }
    


  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 </h4>
        <a href="/register" className="btn btn-primary">Register</a>
    </center>
    </div></div>



  )
}




export default Login

CodePudding user response:

//register

import React,{useEffect, useState} from "react";
import { Registeruser } from "../services/Auth";
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 Registeruser(formdata);
            console.log(data);

            if(data?.data?.name){
                alert("register ok");
                navigate("/");
            }

            else{
                alert("error");
                Window.location.reload();

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

CodePudding user response:

//navbar

import React,{useEffect,useState} from "react";
import { useNavigate} from "react-router-dom";

const Navbar = () => {

    const navigate = useNavigate();
    const [userRole , setuserRole] = useState("")

useEffect(() =>{
    setuserRole(localStorage.getItem("userRole"));
},[])

  useEffect(()=>{
    console.log("userRole",userRole);
}, [userRole])


const handleSubmit = () =>{

    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">Admin Pages</a>
        
        <a style={{ display: userRole == "student" ? "flex" : "none" , textDecoration:"none"}} className="sidebarListItem" href="/student-" aria-current="page">Student Pages</a>



      </div>
    </div>
  </div>  
  <button onClick={handleSubmit} className="btn btn-success" type="submit" style={{ float: "right", marginRight: "10px" , display:userRole ? "flex":"none"}}>
    {"Logout"}
  </button>
</nav>
    </div></div>
  )
}



export default Navbar

CodePudding user response:

//auth js

import axios from 'axios';

const LoginURL ="http://localhost:3000/users/login";
const RegisterURL = "http://localhost:3000/users/register";
const GetAllUsersURL = "http://localhost:3000/users/getAllUsers";
const GetOneUserURL ="http://localhost:3000/users/"
//login

export async function loginfuntion(data){

    let alldata ={
        email: data.email,
        password: data.password
    }

    return await axios.post(LoginURL ,alldata);
}

//register

export async function Registeruser(data){

    let alldata={
        name:data?.name,
        email:data?.email,
        password:data?.password,
        userRole:data?.userRole

}
 return await axios.post(RegisterURL , alldata);


}

//get all users

export async function getAllUsers(){

    return await axios.get(GetAllUsersURL);
}


//get one user

export async function getoneuser(){
    return await axios.get(GetOneUserURL   id)
}













//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;

CodePudding user response:

import React from "react";
import  ReactDOM  from "react-dom/client";
import App from "./App"

const root = ReactDOM.createRoot(document.getElementById("app"));
root.render(<App/>);
  • Related