Welcome to Day 3! In the previous two parts, we have set up our backend and designed the Header, Sidebar & Widgets components in our UI. Before we design the Feed component, we need to implement User Authentication so that we can fetch our posts from the database. What we'll do today:
- Implement Firebase Google Auth
- Setup Redux
- Add Login & Logout functionalities
Firebase Auth
Head over to https://console.firebase.google.com/u/1/ and 'Add project'. Name your project and Create a new 'Web' application and copy/paste the SDK configuration.
Go to the 'Authentication' tab and in the 'Sign-in methods',enable Google . Go ahead and install Firebase in the 'client' directory by using 'npm i firebase'. Create a file named 'firebase.js' in the 'src' folder and copy paste the Firebase configuration alongwith some other imports as such:
Redux
Go ahead and install 'react-redux' and '@reduxjs/toolkit'. Create a folder called 'features' in the src directory and create a new file called 'userSlice.js' in the features folder. This file will include the reducers and actions, namely login and logout for our user. In the userSlice.js:
Create a 'store.js' file in the src directory where we import our userSlice and initialize the global store, so that we can use it anywhere in our app and avoid prop drilling!
With our global Redux store & Firebase Auth set up,all that's left to do is create a Login page which will leverage the Firebase Auth to enable User Login and fill our global user object.
Login
In the 'pages' directory, create a 'Login.jsx' file. For now,it will be a simple page with a Logo and a Login Button. Feel free to customize it as per your needs and add more Authentication Providers!
Let's create a 'handleLogin' utility function which will do just what it's name suggests.
Now,in our App.js let's render Login page/Home page depending upon the user's auth state. The user can visit the 'Home' page only after they have logged in.
Logout
With the Login functionality done, lets add an option to Logout when the user clicks on their Avatar in the Header. Head over to 'Header.jsx' in the 'components' directory.
With our login & logout functionalities implemented, in the next part we will add functionality to Add Question and Fetch Question from our database and render it in the Feed component, making our application fully functional.
Homework
- Add more Providers for Login (Github/Facebook)
- Customize the Login page
References
Code Repo
Redux Toolkit
Firebase
See you in the next part!
Top comments (0)