Navigating to a page on load in react JS - javascript

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

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;

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

Related

Prop is not being passed to component but working with other components

I'm in the process of building a merch e-commerce website for a client utilizing the commerce.js API however I've run into a problem. When passing the "cart" object as a prop to the checkout file it returns as an empty object which breaks the website. The web application passes the "cart" object as a prop in other parts of the code and works just fine. Is there something I'm doing wrong?
Code for reference:
import React, { useState, useEffect } from 'react';
import {Paper, Stepper, Step, StepLabel, Typography, CircularProgress, Divider, Button} from '#material-ui/core';
import { commerce } from '../../../lib/commerce';
import Addressform from '../Addressform';
import Paymentform from '../Paymentform';
const steps =['Shipping Address', 'Payment details'];
const Checkout = ({ cart }) => {
const [activeStep, setActiveStep] = useState(0);
const [checkoutToken, setCheckoutToken] = useState(null);
useEffect (() => {
const generateToken = async () => {
console.log(cart.id);
// returns as undefined
try {
const token = await commerce.checkout.generateToken(cart.id, { type: 'cart' });
console.log(token);
setCheckoutToken(token);
console.log("Success!")
} catch (error) {
console.log(error); //Returns 404 Error Obv
console.log("Didnt work")
}
}
generateToken();
}, []);
const Confirmation = () => (
<>
Confirmation
</>
);
const Form = () => activeStep === 0
? <Addressform />
: < Paymentform />
return(
<>
...
</>
);
};
export default Checkout;

Redirect from a Register Form with React Class in v6

I'm doing a register form in React using a class and I would like to send the user to another page when the register is correct, the problem is that I haven't find any functional way to make it.
.then(data => {
if(data.error != null) {
console.log("Error => "+data.error);
} else {
//Send the user to the login page
}
})
This is the part where I would send him to the login page, I have proved with 'useNavigation' and some more, but I can't find the correct way to get it.
Since react-router-dom v6 supports only hooks.
For implementing the navigate functionality inside a class-based component, you have to create a HOC and pass the hooks as props.
// withRouter.js
import { useNavigate } from 'react-router-dom';
export const withRouter = (Component) => {
const Wrapper = (props) => {
const navigate = useNavigate();
// any other hooks can be added and passed on
return (
<Component
navigate={navigate}
{...props}
/>
);
};
return Wrapper;
};
then on your RegisterForm.jsx you can
import {withRouter} from './withRouter';
class RegisterForm extends React.Component{
//...
yourFunction =() =>{
.then(data => {
if(data.error != null) {
console.log("Error => "+data.error);
} else {
//Send the user to the login page
this.props.navigate('/loginPage');
}
})
}
//...
}
export default withRouter(RegisterForm);
(https://github.com/remix-run/react-router/issues/7256)

Why does Okta-React Login redirect to blank page when using Django?

I am using Okta-React for authentication in my React project and when I run the React test server my login authenticates successfully and redirects to the account page. When I run the React build command and render the build files with Django, my login authenticates properly, but when it redirects back to my site I get a blank /implicit/callback page, no login token or user info, and the code & state gets stuck in the URL. Does anyone know why this is only happening when using Django, and what I can do to resolve this issue?
Here is my authConfig:
const config = {
issuer: 'https://dev-#######.okta.com/oauth2/default',
redirectUri: window.location.origin + '/implicit/callback',
clientId: '#################',
pkce: true
};
export default config;
Here is my accountAuth
import React, { useState, useEffect } from 'react';
import { useOktaAuth } from '#okta/okta-react';
import '../scss/sass.scss';
import "../../node_modules/bootstrap/scss/bootstrap.scss";
import 'react-bootstrap';
const AccountAuth = () => {
const { authState, authService } = useOktaAuth();
const [userInfo, setUserInfo] = useState(null);
useEffect(() => {
if (!authState.isAuthenticated) {
// When user isn't authenticated, forget any user info
setUserInfo(null);
} else {
authService.getUser().then((info) => {
setUserInfo(info);
});
}
}, [authState, authService]); // Update if authState changes
localStorage.setItem("username", userInfo && userInfo.given_name)
const login = async () => {
// Redirect to '/account_page' after login
localStorage.setItem("accountLink", "/account_page")
localStorage.setItem("loginPostingVisibilityStyle", { display: "none" })
localStorage.setItem("postingVisibleStyle", { display: 'block' })
authService.login('/auth_index');
}
const logout = async () => {
// Redirect to '/' after logout
localStorage.setItem("username", null)
localStorage.setItem("accountLink", "/auth_index")
localStorage.setItem("loginPostingVisibilityStyle", { display: "block" })
localStorage.setItem("postingVisibleStyle", { display: 'none' })
authService.logout('/');
}
return authState.isAuthenticated ?
<button className="settings-index" onClick={logout}>Logout</button> :
<button className="settings-index" onClick={login}>Login</button>;
};
export default AccountAuth;
Here is an example of the URL when it's stuck
http://localhost:8000/implicit/callback?code=-mRoU2jTR5HAFJeNVo_PVZsIj8qXuB1-aioFUiZBlWo&state=c9RXCvEgQ4okNgp7C7wPkI62ifzTakC0Ezwd8ffTEb29g5fNALj7aQ63fjFNGGhT
It doesn't look like you're handling the callback to exchange the authorization_code for tokens. You might want to check out Okta's React sample app to see how it works.

How to access a function from React Functional Component in a Normal Javascript File?

Greetings Javascript Developers. I'm stuck in a complex situation now where I need to access a function inside one of my functinal components outside in a normal js file.
Ok So here's what I'm doing: This is my Authorizer.js functional Component.
import React, { createContext, useState, useEffect, useContext } from "react";
import SplashScreen from "react-native-splash-screen";
import { useStore } from "../config/Store";
import { useDatabase } from "../config/Persistence";
import { getSessionCredentials } from "../config/Persistence";
import NavigationDrawer from "./NavigationDrawer";
import AuthStacks from "./AuthStacks";
const AuthContext = createContext();
export const useAuthorization = () => useContext(AuthContext);
export function Authorizer() {
//TODO check whether user is already signed in or not.
const realm = useDatabase();
const { state, dispatch } = useStore();
const [isAuthorized, setAuthorization] = useState(false);
useEffect(() => {
VerifyCredentials();
}, []);
async function VerifyCredentials() {
//TODO Check from Async Storage?
var session = await getSessionCredentials();
console.log("saved session", session);
if (session) {
await DispatchShopData();
await setAuthorization(true);
} else {
await setAuthorization(false);
}
sleep(1000).then(() => {
SplashScreen.hide();
});
}
async function DispatchShopData() {
try {
let shop = await realm.objects("Shop");
await dispatch({ type: "UPDATE_SHOP_DETAILS", payload: shop[0] });
} catch (error) {
console.log("failed to retrieve shop object", error);
}
}
function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
return (
<AuthContext.Provider value={{ setAuthorization }}>
{isAuthorized ? <NavigationDrawer /> : <AuthStacks />}
</AuthContext.Provider>
);
}
This component basically handles my Authentication Flow, whether to show the Navigation Drawer or the Login Screen. Now I have another simple javascript file ApiService.js which does not have any components, only simple js functions.
import Axios from "axios";
import { getAuthToken } from "../config/Persistence";
import { LogoutUser } from "../config/Persistence";
import { Alert } from "react-native";
const BASE_URL = "#########################";
/** Defined my Api Endpoints Here */
let service = Axios.create({
baseURL: BASE_URL,
timeout: 10000,
});
service.interceptors.response.use((response) => {
console.log("[API] response intercepted data", response.data.message);
if (!response.data.status && response.data.tokenExpired) {
//Auth token has Expired. Show user Alert for Session Expired & redirect to login screen.
Alert.alert(
"Your Session has Expired!",
"Don't worry though. You just need to login again & you're set.",
[
{
text: "Continue",
style: "default",
onPress: () => {
LogoutUser()
.then((success) => {
if (success) {
//TODO Find a way to Access this function from Authorizer.js Component.
//setAuthorization(false);
}
})
.catch((error) => {
console.log("failed to logout after session expiry", error);
});
},
},
]
);
}
return response;
});
/** Defined my other api functions called inside my other components */
function TestSampleApi() {
try {
return new Promise(async function (resolve, reject) {
const response = await service.get("https://jsonplaceholder.typicode.com/users");
if (response.data != null) {
resolve(response.data);
} else {
reject(response.status);
}
});
} catch (error) {
console.log("request error", error.message);
}
}
export {
TestSampleApi,
/** Exporting other api functions as well */
};
In my ApiService.js file, I've setup a response interceptors whose job is to catch the default auth token expired response and SignOut user immediately and take him to the Login Screen. Here's now where my issue comes.
In normal scenarios, where I need to access functions from one component inside another component, I can manage is using CreateContext() and useContent() hooks. However, how do I access the useState function setAuthorization in my Authorizer.js components in my ApiService.js file as a normal js function.
I only need to call setAuthorization(false) from my response interceptor block to make the user return to the Login Screen. Problem is idk how to access that state setter function. So any help would be greatly appreciated.

React, GraphQL: How to access render Result from Child in the Parent Component

Hope everyone is staying safe.
I'm sorry I could not find an answer online for my specific situation.
I have a Child component that Queries if the user is logged in and will return true or false (at least thats my expectation).
I want to capture this result in Parent component and display a form if true. But not sure how to do this: I'm getting the same output whether the use is logged in or not.
I have tried several configurations but didn't work. This is is my latest try.
UPDATED Code as noted based on comment 1:
But getting following errors:
Error1:
Warning: Cannot update a component (`EditProfile`) while rendering a different component (`Query`).
in Query (at GetLoggedInUser
Error2:
Uncaught Error: Query(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null.
at reconcileChildFibers
Parent Comp "EditProfile":
import React, { useState, useEffect } from 'react';
import { Query, Mutation } from 'react-apollo';
import { useHistory } from "react-router-dom";
import GetLoggedInUser from '../../../GetLoggedInUser'
// import { GetAuthUser } from './operations.graphql';
const EditProfile = ({match, location}) => {
const reqUser = match.params.username;
const prevUrl = location.pathname;
const history = useHistory();
const [isLoggedIn, setIsLoggedIn] = useState(false);
// const setLoginState = (e) => setIsLoggedIn(e)
return (
/*
<GetLoggedInUser user={reqUser} props={setLoginState}>
{console.log(`After query 'isLoggedIn' is: ${isLoggedIn}`)}
</GetLoggedInUser>
*/
// OLD Code
// <GetLoggedInUser user={reqUser} /> ? "show form" : "don't show form"
//This where I'm having trouble I think?? "Show form" shows up either case.
// ***NEW UPDATED***
<GetLoggedInUser user={reqUser} setIsLoggedIn={setIsLoggedIn}/>
)
}
export default EditProfile;
Child (common) comp "GetLoggedInUser":
import React, { useState, useEffect } from 'react';
import { Query } from 'react-apollo';
import { FontAwesomeIcon } from '#fortawesome/react-fontawesome';
import { AuthUser } from './operations.graphql';
const GetLoggedInUser = ({user, setIsLoggedIn}) => {
const reqUser = user;
//const loggedIn = false;
return (
<Query query={AuthUser}>
{({loading, error, data}) => {
if (loading) return <p><FontAwesomeIcon icon="spinner" size="lg" spin /></p>
if (error) return <p>{`Error: ${error}`}</p>
const authUser = data.authUser.username;
// OLD code
// return ((authUser === reqUser) ? true : false)
// ***NEW UPDATED***
return setIsLoggedIn((authUser === reqUser) ? true : false)
}}
</Query>
)
}
export default GetLoggedInUser;
operations.graphql: (this basically queries context[:current_user] and return it)
query AuthUser {
authUser {
id
username
}
}
Thank you in advance for your time.

Categories

Resources