I'm new to backend programming and building my first full stack project and using Express/Mongoose/Mongo and Passport.js for the first time.
I have built "sign in with Github" functionality and have everything with Passport set up. Now I want to use Redux to store whether or not a user is logged in. If the user is logged in I want to change my navigation bar i.e. if the user isn't logged in one link says "log in", but if the user is logged in the "log in" link changes to "profile".
I know I can use the ternary operator in my React component to toggle the link depending on whether the user is logged in.
How do I use Redux to store whether a user is logged in? Here's what I have so far:
Redux action:
export function loggedIn() {
return {
type: "LOGGED_IN",
loggedIn: false
}
};
Redux reducer:
export default function reducer(state = {
loggedIn: false
}, action) {
switch(action.type) {
case "LOGGED_IN": {
return {
...state,
loggedIn: true
}
}
case "LOGGED_OUT": {
return {
...state,
loggedIn: false
}
}
default: return state;
}
}
I'm my Express route I am using the following middleware:
// Checks if user is not logged in
const authCheck = (req, res, next) => {
if(!req.user) {
// If user is not logged in, redirect them to login page
res.redirect('/auth/login');
}
else {
// If user is logged in call next in router.get
// Would this be the proper place to dispatch to the Redux store
// whether a user is logged in?
dispatch(loggedIn(true));
// After updating the Redux store call next()
next();
}
};
How can I properly store in state whether the user is logged in/out and then access this state in the React component so I can use the ternary operator to choose whether to display "logged in" or "profile" in my navigation bar?