-
Notifications
You must be signed in to change notification settings - Fork 1
/
database.js
79 lines (72 loc) · 1.91 KB
/
database.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
/*===================================================================//
VERSION 8 (current)
//===================================================================*/
import firebase, { database } from "./init-firebase";
// Write data
const writeData = async (data) => {
const { someUsername, someImageUrl } = data;
await database
.ref("users/" + userId)
.set({
username: someUsername,
imageUrl: someImageUrl,
})
.then(() => {
// Success
});
};
// Read data
const userImageRef = database.ref("users/" + userId + "/imageUrl");
const readData = () => {
userImageRef.on("value", (snapshot) => {
const data = snapshot.val();
return data;
});
};
// Read data once
const dbRef = database.ref();
const readDataOnce = async () => {
await dbRef
.child("users")
.child(userId)
.get()
.then((snapshot) => {
if (snapshot.exists()) {
const data = snapshot.val();
console.log(data);
}
});
};
/*===================================================================//
VERSION 9 (beta)
//===================================================================*/
import { database } from "./init-firebase";
import { ref, set, onValue, child } from "firebase/database";
// Write data
const writeData = async (data) => {
const { someUsername, someImageUrl } = data;
await set(ref(database, "users/" + userId), {
username: someUsername,
imageUrl: someImageUrl,
}).then(() => {
// Success
});
};
// Read data
const userImageRef = database.ref("users/" + userId + "/imageUrl");
const readData = () => {
onValue(userImageRef, (snapshot) => {
const data = snapshot.val();
return data;
});
};
// Read data once
const dbRef = ref(database);
const readDataOnce = async () => {
await get(child(dbRef, `users/${userId}`)).then((snapshot) => {
if (snapshot.exists()) {
const data = snapshot.val();
console.log(data);
}
});
};