Reputation:
I am working on user registration setup and stuck on a problem where I am not able to redirect from a page 'localhost:3000/activate/tokenNo.'(Activation.jsx file) on load to my main page (App.jsx file) .
Here is my activation.jsx file :
import React, { useEffect } from 'react';
import { useNavigate } from "react-router-dom";
const Activate = () => {
const navigate = useNavigate();
useEffect(() => {
navigate('/')
}, [navigate])
return (
<div>Activation Page</div>
)
}
export default Activate;
Here is my App.jsx file :
import React from 'react';
export const App = () => {
return <div>Dashboard</div>;
};
export default App ;
My activationController.js file :
exports.activationController = (req,res) => {
const {token} = req.body
if(token){
//Verify the token is valid or not or expired
jwt.verify(token , process.env.JWT_ACCOUNT_ACTIVATION ,
(err , decoded) => {
if(err){
return res.status(401).json({
error: "Expired Token , Signup again"
})
}
else{
//if valid save to database
//Get name email password from token
const {name , email , password} = jwt.decode(token)
const user = new User({
name ,
email ,
passsword
})
user.save((err,user) => {
if(err){
return res.status(401).json({
error: errorHandler(err)
})
}
else{
return res.json({
success: true ,
message: "Signup successful",
user
})
}
})
}
})
}
else{
return res.json({
message: "error happening please try again"
})
}
}
In my auth.routes.js
router.post('/activation', activationController)
I recieved an error in my console --> index.tsx:25 No routes matched location "/activate/tokenNo."
My reference folder --> https://github.com/Mohammed-Abdelhady/FULL-MERN-AUTH-Boilerplate
Upvotes: 2
Views: 5352
Reputation: 33
You may need "Navigate( to="where to go") instead. Leaving the dependencies open in useEffect will make the code run only once at load time. If you include [navigate] it will run every time. Not sure what you are trying to achieve, but Router/Routes/Route may be a better mechanism. If you are doing login/registration, in your login you would have a Link to your registration page. Then you could setup 2 routes, one for Login and one for Registration.
import React, { useEffect } from 'react';
import { Navigate } from "react-router-dom";
const Activate = () => {
useEffect(() => {
Navigate( to='/');
}, [])
return (
<div>Activation Page</div>
)
}
export default Activate;
Upvotes: 1
Reputation: 7193
Often we require to perform some extra action on component or page render initially.
Like, Data fetching, etc.
To implement like this we can use the useEffect hook from react and state our execution into it.
I can't see the useNavigate hook in the latest version of react-router-dom so we can use the useHistory hook.
For Example:
import React, { useEffect } from "react"
import { useHistory } from 'react-router-dom'
const App = () => {
const history = useHistory();
useEffect(() => {
history.push('Page2URL')
}, [history])
return (
<div>Page1</div>
)
}
Upvotes: 0