Home > Mobile >  useNavigate hook not working in my react app
useNavigate hook not working in my react app

Time:02-05

I am trying to develop a page where, after registering yourself, you can login with the OTP, which is gonna get through nodemailer module in react.

I have used postman API to test my REST API. It works fine.

But the main the problem is after sending mail, I canbot go to other page.

import "../styles/mix.css";
import { Navigate, NavLink, useNavigate } from "react-router-dom";
import { useState } from "react";
import { ToastContainer, toast } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
import { sentOtpFunction } from "../services/Apis";

export default function Login() {
  const [email,setEmail]=useState("");
const navigate=useNavigate();
  //sendOtp
  const sendOtp= async (e)=>{
    e.preventDefault();
    if(email===""){
      toast.error("Enter Your Email!");
    }
    else if(!email.includes('@')){
      toast.error("Enter Valid Email!");
    }
    else{
      const data={
        email:email
      }
      
      const response=await sentOtpFunction(data);
      console.log(response);
      if(response.status===200){
        navigate("/user/otp");
      }
      else{
        
        toast.error(response.response.data.error)
      }
    }
  }
  return (
    <>
    <section>
        <div className="form_data">
          <div className="form_heading">
            <h1>Welcome Back, Log In</h1>
            <p>Hi, we are glad you are back. Please login.</p>
          </div>
          <form>
            <div className="form_input">
              <label htmlFor="email">Email</label>
              <input type="email" name="email" onChange={(e)=>setEmail(e.target.value)} id="" placeholder="Enter your Email address"></input>
            </div>
            <button className="btn" onClick={sendOtp}>Login</button>
            <p>Don't have an account? <NavLink to="/register">Sign up</NavLink></p>
          </form>
        </div>
        <ToastContainer/>
        </section>
    </>
  )
}

This is sendOtpFunction:

import {commonrequest} from './ApiCall';
import {BACKEND_URL} from './helper';

 export const registerfunction=async(data)=>{
return await commonrequest("POST",`${BACKEND_URL}/user/register`,data)
 }

 export const sentOtpFunction=async (data)=>{
    return await commonrequest("POST",`${BACKEND_URL}/user/sendotp`,data)

    }
 

This is my apicall.js:

import axios from 'axios';


export const commonrequest= async(methods,url,body,header)=>{
       let config={
        method: methods,
        url,
        headers:header?header:{
            "Content-Type":"application/json"
        },
        data:body
       }
       //axios Instance
       
       return axios(config).then((data)=>{
        return data
       }).catch((error)=>{
        return error
       })
}

This api.js from backend:

require("dotenv").config();
const express=require('express');
const app=express();
const cors=require('cors');

require("./db/conn");
const router=require("./routes/router");
const PORT=4002;

//middleware
app.use(express.json());
app.use(cors());
app.use(router);



app.listen(PORT,()=> console.log("Server connected!!"));

This is routes.js from backend:

const express=require("express");
const router=new express.Router();
const controllers=require("../controllers/userControllers");

// Routes
router.post("/user/register",controllers.userregister);
router.post("/user/sendotp",controllers.userOtpSend);



module.exports=router;

This is usercontrollers file from backend

const users=require("../models/userSchema")
const userotp=require("../models/userOtp");
const nodemailer=require("nodemailer");

//email config
const transporter=nodemailer.createTransport({
    service:"gmail",
    host: 'smtp.gmail.com',
  port: 465,
  secure: true,
    auth:{
        user:process.env.EMAIL,
        pass:process.env.PASSWORD
    }

})



exports.userregister=async (req,res)=>{
     const {fname,email,password}=req.body;
     if(!fname||!email||!password){
        res.status(400).json({error:"Please Enter All Input Data"});
     }
     try{
        const preuser=await users.findOne({email:email});
        
        if(preuser){
            res.status(400).json({error:"This User name is already exist in Our database"})
        }
        else{
            
            const userregister=new users({
                fname,email,password
            });
            
            //here password hashing
            const storeData=await userregister.save();
            res.status(200).json(storeData);
        }
     }
     catch(error){
       res.status(400).json({error:"Invalid Details"})
     }
}
//user send otp
exports.userOtpSend=async(req,res)=>{
    const {email}=req.body;
    
    if(!email){
        res.status(400).json({error:"Please Enter Your Email"})
    }
    try{
        const preuser=await users.findOne({email:email});
        if(preuser){
             const OTP=Math.floor(100000 Math.random()*900000);
             const existEmail=await userotp.findOne({email:email});
             if(existEmail){
                const updateData=await userotp.findByIdAndUpdate({_id:existEmail._id},{
                    otp:OTP
                },{new:true});
                await updateData.save();
const mailOptions={
    from:process.env.EMAIL,
    to:email,
    subject:"Sending Email For Otp Validation",
    text:`OTP:- ${OTP}`
}
transporter.sendMail(mailOptions,(error,info)=>{
    if(error){
        console.log("error",error);
        res.status(400).json({error:"email not send"});
    }
    else{
        console.log("Email sent",info.response);
        res.status()
    }
})

             }
             else{
                const saveOtpData=new userotp({
                    email,otp:OTP
                });
                await saveOtpData.save();
             }
        }
        else{
            res.status(400).json({error:"This User not exist in our Database"});
        }
    }
    catch(error){
           res.status(400).json({error:"Invalid Details",error})
    }
}

CodePudding user response:

Most probably the issue would be the lack of status code in the response after sending the email:

// backend ../controllers/userControllers
console.log("Email sent",info.response);
res.status()

...whereas you expect a 200 code to trigger page navigation:

// Front Login
if(response.status===200){
  navigate("/user/otp");
}

That being said, just res.status() is strange in itself. You probably meant res.send() to properly terminate the handling, Express using 200 status code by default.

Furthermore, by default Axios treats status codes outside the 2xx range as an error (see validateStatus config option). You handle that error in your catch, but silently return the error object, which is not directly the response (but it still holds it in error.response).

  • Related