I am trying to do some basic conditional rendering based on user login. I have my event handlers and axios call in a Login component.
const Login = () => {
const handleChange = event => {
setCustomerLogin({
...customerLogin,
[event.target.name]: event.target.value
});
};
const handleSubmit = e => {
e.preventDefault();
axios
.post("/api/Authentication", customerLogin)
.then(function(response) {
setCustomerLogin(response.data);
console.log(response);
})
.catch(function(error) {
console.log(error);
});
};
My Navbar component is very basic right now and just automatically renders my SignedOutLinks, which are the links I display before a user is logged in.
const Navbar = () => {
return (
<nav className="nav-wrapper blue darken-4">
<div className="container">
<Link to='/' className="brand-logo left">Cars4U</Link>
<SignedOutLinks />
</div>
</nav>
)
};
I would like to define my setCustomerLogin function in App.js and have my Login component call this value. This is my App.js file so far, I am just uncertain how to define the function in my App.js and set the state in my Login component
const [customerLogin, setCustomerLogin] = useState([
{ username: "", password: "" }
]);
function App() {
return(
<div className="App">
<Navbar />
<Switch>
<Route path='/login' component={Login}/>
<Route path='/signup' component={Signup}/>
</Switch>
</div>
);
}
You can pass the state setter(setCustomerLogin) and state value(customerLogin) down to your Login component as props:
const [customerLogin, setCustomerLogin] = useState([
{ username: "", password: "" }
]);
function App() {
return(
<div className="App">
<Navbar />
<Switch>
<Route path='/signup' component={Signup}/>
<Route
path="/login"
render={() =>
<Login
customerLogin={customerLogin}
setCustomerLogin={setCustomerLogin}
/>}
/>
</Switch>
</div>
);
}
Note that I used a little different syntax for routing the Login component, you are still going to get the same result, only that now you can pass in any props you want to the component to render. You can read more about that kind of routing here.
And then, you can access them in the Login component via props:
const Login = ({setCustomerLogin, customerLogin}) => {
const handleChange = event => {
setCustomerLogin({
...customerLogin,
[event.target.name]: event.target.value
});
};
const handleSubmit = e => {
e.preventDefault();
axios
.post("/api/Authentication", customerLogin)
.then(function(response) {
setCustomerLogin(response.data);
console.log(response);
})
.catch(function(error) {
console.log(error);
});
};
Related
I don't know why, changing the props state inside useEffect causes infinite loop of errors. I used them first locally declaring within the function without using props which was running ok.
EDIT:
Home.js
import Axios from "axios";
import React, { useEffect, useState } from "react";
function Home(props) {
// const [details, setDetails] = useState({});
// const [login, setLogin] = useState(false);
useEffect(() => {
try {
const data = localStorage.getItem("expensesAccDetails");
if (data) {
Axios.post("http://localhost:3001/eachCollectionData", {
collection: data,
}).then((res) => {
if (res.data.err) {
console.log("Error");
} else {
console.log(res.data[0]);
props.setLogin(true);
props.setUserdetails(res.data[0]);
}
});
}
} catch (err) {
console.log(err);
}
}, []);
return props.login ? (
<div>
<div>Welcome {props.setUserdetails.FullName}</div>
</div>
) : (
<div>You need to login first</div>
);
}
export default Home;
App.js
function App() {
const [login, setLogin] = useState(false);
const [userdetails, setUserdetails] = useState({});
return (
<Router>
<Routes>
<Route
path="/Home"
element={
<>
<Home
setLogin={setLogin}
login={login}
setUserdetails={setUserdetails}
userdetails={userdetails}
/>
<Bars login={login} />
</>
}
/>
<Routes>
<Router>
);
Here I initialized the states directly in App.js so I don't have to declare it on every page for the route renders. I just passed them as props to every component.
I suggest to create a componente Home with the post and two sub-component inside:
const Home = () => {
const [userDetails, setUserDetails] = useState({});
const [login, setLogin] = useState(false);
useEffect(() => {
// api call
}, []);
return (
<>
<Welcome login={login} details={userDetails} />
<Bars login={login} details={userDetails} />
</>
);
};
where Welcome is the following:
const Welcome = ({ userdetails, login }) => (
<>
login ? (
<div>
<div>Welcome {userdetails.FullName}</div>
</div>
) : (
<div>You need to login first</div>
);
</>
);
A better solution is to use only one state variable:
const [userDetails, setUserDetails] = useState(null);
and test if userDetails is null as you test login is true.
An alternative if you have to maintain the call as you write before, you can use two state as the follow:
function App() {
const [userdetails, setUserdetails] = useState(null);
return (
<Router>
<Routes>
<Route
path="/Home"
element={
<>
<Home
setUserdetails={setUserdetails}
/>
<Bars login={!!userdetails} />
</>
}
/>
<Routes>
<Router>
);
and on Home component use a local state:
const Home = ({setUserdetails}) => {
const [userDetailsLocal, setUserDetailsLocal] = useState(null);
useEffect(() => {
// api call
// ... on response received:
setUserdetails(res.data[0]);
setUserDetailsLocal(res.data[0]);
// ...
}, []);
userDetailsLocal ? (
<div>
<div>Welcome {userDetailsLocal.FullName}</div>
</div>
) : (
<div>You need to login first</div>
);
};
I advise to follow Max arquitecture for your solution. the problem lies in the Router behavior. React Router is not part of React core, so you must use it outside your react logic.
from documentation of React Router:
When you use component (instead of render or children, below) the router uses React.createElement to create a new React element from the given component. That means if you provide an inline function to the component prop, you would create a new component every render.
https://v5.reactrouter.com/web/api/Route/component
Edit:
ok, you make me write it. A solution could be like:
function App() {
const [login, setLogin] = useState(false);
const [userdetails, setUserdetails] = useState({});
useEffect(() => {
try {
const data = localStorage.getItem("expensesAccDetails");
if (data) {
Axios.post("http://localhost:3001/eachCollectionData", {
collection: data,
}).then((res) => {
if (res.data.err) {
console.log("Error");
} else {
console.log(res.data[0]);
setLogin(true);
setUserdetails(res.data[0]);
}
});
}
} catch (err) {
console.log(err);
}
}, []);
return (
<Router>
<Routes>
<Route
path="/Home"
element={
<>
<Home
login={login}
userdetails={userdetails}
/>
<Bars login={login} />
</>
}
/>
<Routes>
<Router>
);
I am working on a react application.
I am trying to create login and register functionality.
I have a Authorized.tsx component which looks like this
export const Authorized = (props: authorizedProps) => {
const [isAuthorized, setIsAuthorized] = useState(true);
const { claims } = useContext(AuthContext);
useEffect(() => {
if (props.role) {
const index = claims.findIndex(
claim => claim.name === 'role' && claim.value === props.role)
setIsAuthorized(index > -1);
} else {
setIsAuthorized(claims.length > 0);
}
}, [claims, props.role]);
return (
<>
{isAuthorized ? props.authorized : props.notAuthorized}
</>
);
};
interface authorizedProps {
authorized: ReactElement;
notAuthorized?: ReactElement;
role?: string;
}
This component hides and shows diffrent kind of components depending on if the user is authorized or not.
I am using this component to only show the Login.tsx component for users that are not logged in. I dont want anyone who is not logged in to be able to visit the website.
In my Index.tsx I am using the Authorized.tsx component like this
const Index = () => {
const [claims, setClaims] = useState<claim[]>([
// { name: "email", value: "test#hotmail.com" },
]);
return (
<div>
<BrowserRouter>
<AuthContext.Provider value={{ claims, update: setClaims }}>
<Authorized authorized={<App />} notAuthorized={<Login />} />
</AuthContext.Provider>
</BrowserRouter>
</div>
);
};
All the authorized users will be able to visit the site, everyone else will be asked to log in.
However, the problem I have is when I tried adding the Register.tsx component into the Login.tsx component as a navigational link.
I wish to be able to navigate between Register and Login
This is how the Login.tsx component looks like
export const Login = () => {
return (
<>
<h3>Log in</h3>
<DisplayErrors errors={errors} />
<AuthForm
model={{ email: "", password: "" }}
onSubmit={async (values) => await login(values)}
BtnText="Log in" />
<Switch>
<Route path="/register">
<Register />
</Route>
<Link to='/register'>Register</Link>
</Switch>
</>
);
};
But what actually happends when I press the 'Register' link is that the Register component gets added below the Login component
Before pressing the 'Register' link
After pressing the 'Register' link
I understand it has something to do with the Authorized.tsx component in Index.tsx.
That I am telling it to only show the Login component when not authorized.
But I dont know how I could fix it so I will be able to navigate between the Login and the Register
All help I could get would be much appreciated!
Thanks
With the current implementation you are rendering a Login component that then also renders a route for a Register component to be rendered on. Login remains mounted and rendered the entire time. From what you describe you want to render Login and Register each on their own route.
Abstract both these components into a parent component that manages the route matching and rendering.
Example
const Unauthenticated = () => (
<Switch>
<Route path="/register" component={Register} />
<Route component={Login} />
</Switch>
);
...
export const Login = () => {
...
return (
<>
<h3>Log in</h3>
<DisplayErrors errors={errors} />
<AuthForm
model={{ email: "", password: "" }}
onSubmit={login}
BtnText="Log in"
/>
<Link to='/register'>Register</Link>
</>
);
};
...
const Index = () => {
const [claims, setClaims] = useState<claim[]>([
// { name: "email", value: "test#hotmail.com" },
]);
return (
<div>
<BrowserRouter>
<AuthContext.Provider value={{ claims, update: setClaims }}>
<Authorized
authorized={<App />}
notAuthorized={<Unauthenticated />}
/>
</AuthContext.Provider>
</BrowserRouter>
</div>
);
};
So I have a straight forward app that requires you to login to see a dashboard. I've based my auth flow off of https://reactrouter.com/web/example/auth-workflow which in return bases their flow off of https://usehooks.com/useAuth/
Currently, when a user logs in it calls a function within the context provider to sign in and that function updates the state of the context with the user data retrieved from the server. This is reflected in React dev tools under my context providers as shown in the teacher attribute:
When the context state has successfully been updated I then use useHistory().push("dashboard/main") from the react-router API to go to the dashboard page. The dashboard is a consumer of the context provider but the teacher value is still null when I try rendering the page- even though React dev tools clearly shows the value has been updated. When I log in again, the dashboard will successfully render, so, ultimately, it takes two context updates in order for my Dashboard to reflect the changes and render. See my following code snippets (irrelevant code has been redacted):
App.js
const App = () => {
return (
<AuthProvider>
<div className="App">
<Switch>
<Route path="/" exact >
<Home setIsFetching={setIsFetching} />
</Route>
<ProtectedRoute path="/dashboard/:page" >
<Dashboard
handleToaster={handleToaster}
/>
</ProtectedRoute>
<ProtectedRoute path="/dashboard">
<Redirect to="/dashboard/main"/>
</ProtectedRoute>
<Route path="*">
<PageNotFound/>
</Route>
</Switch>
<Toaster display={toaster.display} setDisplay={(displayed) => setToaster({...toaster, display: displayed})}>{toaster.body}</Toaster>
</div>
</AuthProvider>
);}
AuthProvider.js
const AuthProvider = ({children}) => {
const auth = useProvideAuth();
return(
<TeacherContext.Provider value={auth}>
{children}
</TeacherContext.Provider>
);};
AuthHooks.js
export const TeacherContext = createContext();
export const useProvideAuth = () => {
const [teacher, setTeacher] = useState(null);
const memoizedTeacher = useMemo(() => ({teacher}), [teacher]);
const signin = (data) => {
fetch(`/api/authenticate`, {method: "POST", body: JSON.stringify(data), headers: JSON_HEADER})
.then(response => Promise.all([response.ok, response.json()]))
.then(([ok, body]) => {
if(ok){
setTeacher(body);
}else{
return {...body};
}
})
.catch(() => alert(SERVER_ERROR));
};
const register = (data) => {
fetch(`/api/createuser`, {method: "POST", body: JSON.stringify(data), headers: JSON_HEADER})
.then(response => Promise.all([response.ok, response.json()]))
.then(([ok, body]) => {
if(ok){
setTeacher(body);
}else{
return {...body};
}
})
.catch(() => alert(SERVER_ERROR));
};
const refreshTeacher = async () => {
let resp = await fetch("/api/teacher");
if (!resp.ok)
throw new Error(SERVER_ERROR);
else
await resp.json().then(data => {
setTeacher(data);
});
};
const signout = () => {
STORAGE.clear();
setTeacher(null);
};
return {
...memoizedTeacher,
setTeacher,
signin,
signout,
refreshTeacher,
register
};
};
export const useAuth = () => {
return useContext(TeacherContext);
};
ProtectedRoute.js
const ProtectedRoute = ({children, path}) => {
let auth = useAuth();
return (
<Route path={path}>
{
auth.teacher
? children
: <Redirect to="/"/>
}
</Route>
);
};
Home.js
const Home = ({setIsFetching}) => {
let teacherObject = useAuth();
let history = useHistory();
const handleFormSubmission = (e) => {
e.preventDefault();
const isLoginForm = modalContent === "login";
const data = isLoginForm ? loginObject : registrationObject;
const potentialSignInErrors = isLoginForm ?
teacherObject.signin(data) : teacherObject.register(data);
if(potentialSignInErrors)
setErrors(potentialSignInErrors);
else{
*******MY ATTEMPT TO PUSH TO THE DASHBOARD AFTER USING TEACHEROBJECT.SIGNIN********
history.replace("/dashboard/main");
}
};
};)};
Dashboard.js
const Dashboard = ({handleToaster}) => {
const [expanded, setExpanded] = useState(true);
return (
<div className={"dashboardwrapper"}>
<Sidebar
expanded={expanded}
setExpanded={setExpanded}
/>
<div className={"dash-main-wrapper"}>
<DashNav/>
<Switch>
<Route path="/dashboard/classroom" exact>
<Classroom handleToaster={handleToaster} />
</Route>
<Route path="/dashboard/progressreport" exact>
<ProgressReport/>
</Route>
<Route path="/dashboard/help" exact>
<Help/>
</Route>
<Route path="/dashboard/goalcenter" exact>
<GoalCenter />
</Route>
<Route path="/dashboard/goalcenter/create" exact>
<CreateGoal />
</Route>
<Route path="/dashboard/profile" exact>
<Profile />
</Route>
<Route path="/dashboard/test" exact>
<Test />
</Route>
<Route path="/dashboard/main" exact>
<DashMain/>
</Route>
</Switch>
</div>
</div>
);
};
Let me know if there's anything that stands out to you that would be preventing my Dashboard from rendering with the updated context values the first time instead of having to update it twice. Do let me know if you need more insight into my code or if I missed something- I'm also fairly new to SO. Also, any pointers on the structure of my app would be greatly appreciated as this is my first React project. Thank you.
I think the problem is in the handleFormSubmission function:
const handleFormSubmission = (e) => {
e.preventDefault();
const isLoginForm = modalContent === "login";
const data = isLoginForm ? loginObject : registrationObject;
const potentialSignInErrors = isLoginForm ?
teacherObject.signin(data) : teacherObject.register(data);
if(potentialSignInErrors)
setErrors(potentialSignInErrors);
else{
history.replace("/dashboard/main");
}
};
You call teacherObject.signin(data) or teacherObject.register(data) and then you sequentially change the history state.
The problem is that you can't be sure the teacher state has been updated, before history.replace is called.
I've made a simplified version of your home component to give an example how you could approach the problem
function handleSignin(auth) {
auth.signin("data...");
}
const Home = () => {
const auth = useAuth();
useEffect(() => {
if (auth.teacher !== null) {
// state has updated and teacher is defined, do stuff
}
}, [auth]);
return <button onClick={() => handleSignin(auth)}>Sign In</button>;
};
So when auth changes, check if teacher has a value and do something with it.
I'm setting up a basic authentication system with React and while signup and login actions correctly redirect and render the appropriate components, my logout action redirects to the protected route and renders the associated component, even though the authentication variable managed with the context API is successfully updated when logging out. The whole operation works in the end, as when I'm refreshing the page, I am successfully redirected to my login page.
I'm using Node.js to manage my sessions and dispatching the logout action works well as, as I said, the variable used with the Context API is updated. I'm using the Effect Hook on my Header component where the logout is initiated and I can see the auth variable being changed.
Here is my code:
AppRouter.js
export const history = createBrowserHistory();
const AppRouter = () => (
<Router history={history}>
<Switch>
<PublicRoute path="/" component={AuthPage} exact={true} />
<PrivateRoute path="/dashboard" component={DashboardPage} />
<Route component={NotFoundPage} />
</Switch>
</Router>
);
PublicRoute.js
const PublicRoute = ({ component: Component, ...rest }) => {
const { uid } = useContext(AuthContext);
useEffect(() => {
console.log("Public Route - Variable set to:", uid);
}, [uid])
return (
<Route
render={props =>
uid !== undefined ? (
<Redirect to="/dashboard" />
) : (
<Component {...props}/>
)
}
{...rest}
/>
)
};
PrivateRoute.js
const PrivateRoute = ({ component: Component, ...rest }) => {
const { uid } = useContext(AuthContext);
useEffect(() => {
console.log("Private Route - Variable set to:", uid);
}, [uid])
return (
<Route
render={props =>
uid !== undefined ? (
<div>
<Header />
<Component {...props}/>
</div>
) : (
<Redirect to="/" />
)
}
{...rest}
/>
)
};
Header.js
export const Header = () => {
const { uid, dispatch } = useContext(AuthContext);
useEffect(() => {
console.log("Header - Variable set to:", uid);
// console.log("HIST", history);
}, [uid])
const logout = async () => {
const result = await startLogout();
if (result.type !== undefined) {
dispatch(result); // Works well
// window.location.href = '/';
// history.push('/');
history.replace('/');
} else {
console.log(result);
}
}
return (
<header className="header">
<div className="container">
<div className="header__content">
<Link className="header__title" to="/dashboard">
<h1>A React App</h1>
</Link>
<button className="button button--link" onClick={logout}>Logout</button>
</div>
</div>
</header>
);
};
I tried both history.push('/') and history.replace('/'). Both these 2 methods work well as if I switch the path to an unknown route, my component that handles 404 is successfully rendered.
Below is my console output when I click the logout button. As you can see, the auth variable is well updated to undefined but that does not prevent my router to keep showing me the protected route. The router should not redirect me to the dashboard as my auth variable is set to undefined after logging out.
Header - Variable set to: {uid: undefined}
Private Route - Variable set to: {uid: undefined}
Public Route - Variable set to: {uid: undefined}
Header - Variable set to: {uid: undefined}
Private Route - Variable set to: {uid: undefined}
For the time being I'm using window.location.href = '/'; which works well, as it automatically reload the root page but I'd like to stick to react-router. Any thoughts? Thanks
in the private route pass renders props.. like this:
const PrivateRoute = ({ component: Component, ...rest }) => {
const { uid } = useContext(AuthContext);
useEffect(() => {
console.log("Private Route - Variable set to:", uid);
}, [uid])
return (
<Route
render={props =>
uid !== undefined ? (
<div>
<Header {...props} />
<Component {...props}/>
</div>
) : (
<Redirect to="/" />
)
}
{...rest}
/>
)
};
then in header use props to push history:
export const Header = (props) => {
const { uid, dispatch } = useContext(AuthContext);
useEffect(() => {
console.log("Header - Variable set to:", uid);
// console.log("HIST", history);
}, [uid])
const logout = async () => {
const result = await startLogout();
if (result.type !== undefined) {
dispatch(result); // Works well
// window.location.href = '/';
// history.push('/');
props.history.push('/');
} else {
console.log(result);
}
}
I have a question regarding lifting state up, I am aware that his is a frequently asked question on here but I hope someone will try to help me understand.
Problem: I have a login component consisting of a form component in which I do my fetch call to execute the login. I want to keep the token I get from my fetch call and save it in the App component so I can use this token and pass it down other pages/components.
So to begin with, I start with my code in my App.js / the parent component?
In here i manage my Routes, and this is also her that I want to store my state.
I pass down the token from this state to the Login component as seen on the Route that renders the Login component.
From what I read, props are not mutable so this actually doesn't work the way I thought out? I made the handleToken function but I will return to that.
export default class App extends Component {
state = {
token: "",
regNo: "",
};
handleToken = (token) => {
this.setState({ token: token})
}
render() {
console.log(this.state.token);
return (
<Router >
<div>
<Header />
<Navbar isLoggedIn={this.state.token} />
<Switch>
<Route exact path="/" render={() => <Home />} />
<Route path="/profile" render={() => <Profile userToken={this.state.token} />} />
<Route path="/login" render={() => <Login userToken={this.state.token} />} />
<Route path="/register" render={() => <Register />} />
<Route path="/carpage" render={() => <CarPage regNo={this.state.regNo} />} />
<Route path="/find-rental" render={() => <FindRental regNo={this.state.regNo} setRegno={this.setRegno}/>} />
<Route path="/rent-out-car" render={() => <RentOutCar />} />
<Route component={NoMatch} />
</Switch>
</div>
</Router >
);
};
Now we move down to the Login component. This component consist of multiple other components that makes up the login page. One of which is the FormContainer where the fetch call for the Login happens.
const Login = (props) => (
<Container fluid={true}>
<BrandRow>
</BrandRow>
<FormRow>
<FormContainer /* userToken={this.props.userToken} */ />
</FormRow>
</Container>
);
export default Login;
(Not sure why it wouldn't render it properly as a code sample, so it went into code snippet)
So as you can see in this Login component, I have the FormContainer which it were all the action happens.
Let me show you:
class FormContainer extends Component {
state = {
userName: '',
password: '',
};
handleChange = event => {
const target = event.target;
const value = target.value;
const name = target.name;
this.setState({ [name]: value });
}
handleSubmit = event => {
event.preventDefault();
const credentials = { username: this.state.userName, password: this.state.password };
this.login(credentials);
}
login = credentials => {
const url = "https://fenonline.dk/SYS_Backend/api/login";
const postHeader = {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(credentials)
};
fetch(url, postHeader).then(res => {
if (!res.ok) { throw Error(res.status + ": " + res.statusText + " | Wrong username or password!"); }
return res.json();
}).then(data => {
this.props.userToken = data.token;
alert("You have succesfully logged in!" + data.token);
this.props.history.push('/profile')
}).catch(error => alert(error));
}
render() {
const { userName, password } = this.state;
return (
<Container>
<Form onSubmit={this.handleSubmit}>
<Title>Sign In</Title>
<Input
type="text"
name="userName"
value={userName}
onChange={this.handleChange}
placeholder="Username.."
/>
<Input
type="password"
name="password"
value={password}
onChange={this.handleChange}
placeholder="Password.."
/>
<Button type="submit">Sign In</Button>
<Button onClick={() => this.props.history.push('/register')}>Register</Button>
</Form>
<Text>Rental service created by users for users.</Text>
</Container>
);
}
}
export default withRouter(FormContainer);
What you want to look at here is the login function, where I created the fetch call and this is where i get the token that i want to my lifted up state to store. Now i try and set it by saying this.props.userToken = data.token; but if props are immuteable how do I do this?
In order to lift state to your top level component, you need to pass your handleToken function into your login component as a prop.
<Route path="/login" render={() => <Login userToken={this.state.token} handleToken={this.handleToken} />} />
Then you will need to pass that into your FormContainer component as a prop as well.
<FormContainer handleToken={this.props.handleToken} />
Lastly, in your fetch, you'll need to call this method in the second .then() instead of trying to assign the token to a prop.
this.props.handleToken(data.token)
This will allow the state to be lifted up to the parent and then allow the token to be passed as a prop to your other components.