This is a memo when I create a to-do list which has a feature of user authentication (Demo here/ Code here).
Install Firebase into your project folder
1. Get started
Sign up Firebase and click “Get started”.
2. Create a project
Click “Add project”
3. Decide your project name
Enter your project name and click “Continue”
4. Click “Continue”
5. Choose your account and Click “Create Project”
You can omit this process if you disable Google Analytics.
6. Project is created in a while
Click “Continue” to start your project.
7. Click “</>” to set up your app
8. Decide your app nickname
Enter your app name and click “Register app”
9. Obtain a config snippet and an install command.
10. install firebase into your local project folder
Go to your project folder and run this command.
npm install firebase
11. Create a config file for firebase app.
Copy the config information you got and paste it in your config file.
// example (assume in config.js)
export const firebaseConfig = {
// configuration information
}
12. Initialize Firebase where you want to use it
Import initializeApp from firebase/app and firebaseConfig from config.js
// example (assume in App.js and you have config.js)
import { initializeApp } from "firebase/app"
import { firebaseConfig } from "./config.js"
initializeApp(firebaseConfig)
function App(){
...
}
export default App;
More information is available here.
Use Realtime Database
1. Go to Realtime Database page
2. Click “Create Database”
3. Choose a region and click “Next”
4. Choose a mode
I chose test mode first to test and changed rules after I added user authentication.
5. Copy the database URL
6. Add databaseURL in your config.js
export const firebaseConfig = {
// configuration information
databaseURL:"https://databaseName.firebaseio.com"
}
const app = initializeApp(firebaseConfig);
export const db = getDatabase(app);
7. Get a reference to the database service
// example
import { initializeApp } from 'firebase/app';
import { getDatabase } from "firebase/database";
import { db } from "./config.js"
Official information about getting start Firebase Realtime Database is provided here.
8. Read Data
Here is an example to read data from a Realtime database by using onValue and ref (visit here for more information)
const auth = getAuth();
const uid = useSelector((state) => state.auth.uid);
const dbRef = ref(db, `notes/${uid}`);
const readData = useCallback(() => {
onValue(dbRef, (*snapshot*) => {
const data = snapshot.val();
const loadedList = [];
for (const key in data) {
loadedList.push({
id: key,
title: data[key].title,
description: data[key].description,
});
}
setList(loadedList);
setInit(false);
});
}, [dbRef]);
9. Update Data
This is an example to manipulate an existing database. Here I use update to add another item to the database. You can use set if you want to override your database.
const newPostKey = push(child(ref(db), "notes")).key;
const updates = {};
updates[`/notes/${uid}/${newPostKey}`] = item;
update(ref(db), updates);
readData();
10. Delete Data
You can delete a certain data by remove method with providing data path.
// General syntax
remove(ref(db, path)
// an example to delete a specific data of a specific user
remove(ref(db, `notes/${uid}/${id}`));
11. Manage the database rule
A common way to secure your database is authentication. Here is an example that allows only an authenticated user can read and write her/his data. For more information about security and rules, please visit here.
{
"rules": {
"notes": {
"$uid": {
".read": "$uid === auth.uid"
".write": "$uid === auth.uid"
}
}
}
}
Use Authentication
1. Click “Authentication”
2. Click “Get started”
3. Choose method
I used Email/Password for this project.
4. Enable Email/Password method and click “Save”
Then you will see this page. Official information is available here.
5. Add sign up feature
Use createUserWithEmailAndPassword.
// an example
import { getAuth, createUserWithEmailAndPassword } from "firebase/auth";
const auth = getAuth();
const [email, setEmail] = useState()
const [password, setPassword] = useState()
createUserWithEmailAndPassword(auth, email, password)
.then((userCredential) => {
// Signed in
const user = userCredential.user;
// ...
})
.catch((error) => {
const errorCode = error.code;
const errorMessage = error.message;
// ..
});
6. Add login feature
Use signInWithEmailAndPassword.
// an example
import { getAuth, signInWithEmailAndPassword } from "@firebase/auth";
const Login = () => {
const inputEmailRef = useRef();
const inputPasswordRef = useRef();
const auth = getAuth();
const loginHandler = (event) => {
event.preventDefault();
const email = inputEmailRef.current.value;
const password = inputPasswordRef.current.value;
signInWithEmailAndPassword(auth, email, password)
.then((userCredential) => {
// Manage login
})
.catch((error) => {
// Manage error
});
};
7. Add logout feature
Use signOut.
import { getAuth, signOut } from "firebase/auth";
const auth = getAuth();
const logoutHandler = () => {
signOut(auth)
.then(() => {
// Manage sign out
})
.catch((error) => {
// Manage error
});
};
Please visit here for more detailed information.
Thank you for reading :)
The original article is here
Top comments (0)