New to react and working on an application with authentication/logging in. It currently works but feels hacked together. Right now I have my isAuthenticated sta
If you are using an application where the authentication lasts only for one session, storing it in state is enough. But do note that this means, the user will lose the authenticated status on page refresh.
Here is an example using React Context, where we create context using createContext and use Consumer to access it across the application.
const AuthenticationContext = React.createContext();
const { Provider, Consumer } = AuthenticationContext;
function Login(props) {
return (
{
value=>
}
);
}
function Logout() {
return (
{
value=>
}
);
}
function AnotherComponent() {
return (
{
value=>{
return value.isAuthenticated?
Logged in
:
Not Logged in
}
}
);
}
class App extends React.Component {
constructor(props) {
super(props);
this.login = ()=> {
this.setState({
isAuthenticated: true
});
}
this.logout = ()=> {
this.setState({
isAuthenticated: false
});
}
this.state = {
isAuthenticated: false,
login: this.login,
logout: this.logout
}
}
render() {
return (
);
}
}
ReactDOM.render( , document.getElementById("root"));
https://reactjs.org/docs/context.html#reactcreatecontext