Skip to content

Commit 97f9886

Browse files
authored
Merge pull request #3 from briandesousa/logrocket-blog
add firebase anonymous auth and capture user who creates each document
2 parents b051678 + aa83baf commit 97f9886

File tree

7 files changed

+53
-36
lines changed

7 files changed

+53
-36
lines changed

src/App.js

Lines changed: 23 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -12,28 +12,33 @@ import useQueryString from './hooks/useQueryString'
1212

1313
function App() {
1414

15-
const [user, setUser] = useState()
15+
const [user, setUser] = useState();
16+
const [userId, setUserId] = useState();
1617
const [groceryList, setGroceryList] = useState();
1718
const [error, setError] = useState();
1819

1920
// Use a custom hook to subscribe to the grocery list ID provided as a URL query parameter
2021
const [groceryListId, setGroceryListId] = useQueryString('listId');
2122

22-
// Use an effect to load the grocery list from the database
23+
// Use an effect to authenticate and load the grocery list from the database
2324
useEffect(() => {
24-
if (groceryListId) {
25-
FirestoreService.getGroceryList(groceryListId)
26-
.then(groceryList => {
27-
if (groceryList.exists) {
28-
setError(null);
29-
setGroceryList(groceryList.data());
30-
} else {
31-
setError('grocery-list-not-found');
32-
setGroceryListId();
33-
}
34-
})
35-
.catch(() => setError('grocery-list-get-fail'));
36-
}
25+
FirestoreService.authenticateAnonymously().then(userCredential => {
26+
setUserId(userCredential.user.uid);
27+
if (groceryListId) {
28+
FirestoreService.getGroceryList(groceryListId)
29+
.then(groceryList => {
30+
if (groceryList.exists) {
31+
setError(null);
32+
setGroceryList(groceryList.data());
33+
} else {
34+
setError('grocery-list-not-found');
35+
setGroceryListId();
36+
}
37+
})
38+
.catch(() => setError('grocery-list-get-fail'));
39+
}
40+
})
41+
.catch(() => setError('anonymous-auth-failed'));
3742
}, [groceryListId, setGroceryListId]);
3843

3944
function onGroceryListCreate(groceryListId, userName) {
@@ -56,19 +61,19 @@ function App() {
5661

5762
// render a scene based on the current state
5863
if (groceryList && user) {
59-
return <EditList {...{ groceryListId, user, onCloseGroceryList}}></EditList>;
64+
return <EditList {...{ groceryListId, user, onCloseGroceryList, userId}}></EditList>;
6065
} else if(groceryList) {
6166
return (
6267
<div>
6368
<ErrorMessage errorCode={error}></ErrorMessage>
64-
<JoinList users={groceryList.users} {...{groceryListId, onSelectUser, onCloseGroceryList}}></JoinList>
69+
<JoinList users={groceryList.users} {...{groceryListId, onSelectUser, onCloseGroceryList, userId}}></JoinList>
6570
</div>
6671
);
6772
}
6873
return (
6974
<div>
7075
<ErrorMessage errorCode={error}></ErrorMessage>
71-
<CreateList onCreate={onGroceryListCreate}></CreateList>
76+
<CreateList onCreate={onGroceryListCreate} userId={userId}></CreateList>
7277
</div>
7378
);
7479
}

src/components/ErrorMessage/ErrorMessage.js

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@ function ErrorMessage(props) {
77

88
function getErrorMessage() {
99
switch(errorCode) {
10+
case 'anonymous-auth-failed':
11+
return 'Anonymous authentication failed. Try again.'
1012
case 'grocery-list-not-found':
1113
return 'The grocery list could not be found. Try creating a new one.';
1214
case 'grocery-list-get-fail':

src/scenes/CreateList/CreateList.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ import ErrorMessage from '../../components/ErrorMessage/ErrorMessage';
55

66
function CreateList(props) {
77

8-
const { onCreate } = props;
8+
const { onCreate, userId } = props;
99

1010
const [ error, setError ] = useState();
1111

@@ -19,7 +19,7 @@ function CreateList(props) {
1919
return;
2020
}
2121

22-
FirestoreService.createGroceryList(userName)
22+
FirestoreService.createGroceryList(userName, userId)
2323
.then(docRef => {
2424
onCreate(docRef.id, userName);
2525
})

src/scenes/EditList/AddItem/AddItem.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ import ErrorMessage from '../../../components/ErrorMessage/ErrorMessage'
66

77
function AddItem(props) {
88

9-
const { groceryListId } = props;
9+
const { groceryListId, userId } = props;
1010

1111
const [error, setError] = useState('');
1212

@@ -20,7 +20,7 @@ function AddItem(props) {
2020
return;
2121
}
2222

23-
FirestoreService.addGroceryListItem(itemDesc, groceryListId)
23+
FirestoreService.addGroceryListItem(itemDesc, groceryListId, userId)
2424
.then(() => document.addItemForm.reset())
2525
.catch(reason => {
2626
if (reason.message === 'duplicate-item-error') {

src/scenes/EditList/EditList.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ import ItemList from './ItemList/ItemList';
55

66
function EditList(props) {
77

8-
const { groceryListId, user, onCloseGroceryList } = props;
8+
const { groceryListId, user, onCloseGroceryList, userId } = props;
99

1010
function onCreateListClick(e) {
1111
e.preventDefault();
@@ -21,7 +21,7 @@ function EditList(props) {
2121
</header>
2222
<div className="edit-container">
2323
<div className="add-item-column">
24-
<AddItem {...{groceryListId}}></AddItem>
24+
<AddItem {...{groceryListId, userId}}></AddItem>
2525
</div>
2626
<div className="list-column">
2727
<ItemList {...{groceryListId}}></ItemList>

src/scenes/JoinList/JoinList.js

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ import * as FirestoreService from '../../services/firestore';
55

66
function JoinList(props) {
77

8-
const { users, groceryListId, onSelectUser, onCloseGroceryList } = props;
8+
const { users, groceryListId, onSelectUser, onCloseGroceryList, userId } = props;
99

1010
const [ error, setError ] = useState();
1111

@@ -32,11 +32,8 @@ function JoinList(props) {
3232
if (users.find(user => user.name === userName)) {
3333
onSelectUser(userName);
3434
} else {
35-
FirestoreService.addUserToGroceryList(userName, groceryListId)
36-
.then(() => {
37-
onSelectUser(userName);
38-
document.addUserToListForm.reset();
39-
})
35+
FirestoreService.addUserToGroceryList(userName, groceryListId, userId)
36+
.then(() => onSelectUser(userName))
4037
.catch(() => setError('add-user-to-list-error'));
4138
}
4239
}

src/services/firestore.js

Lines changed: 19 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import * as firebase from "firebase/app";
22
import "firebase/firestore";
3+
import "firebase/auth";
34

45
const firebaseConfig = {
56
apiKey: process.env.REACT_APP_FIREBASE_API_KEY,
@@ -10,11 +11,19 @@ const firebaseConfig = {
1011
firebase.initializeApp(firebaseConfig);
1112
const db = firebase.firestore();
1213

13-
export const createGroceryList = (userName) => {
14+
export const authenticateAnonymously = () => {
15+
return firebase.auth().signInAnonymously();
16+
};
17+
18+
export const createGroceryList = (userName, userId) => {
1419
return db.collection('groceryLists')
1520
.add({
1621
created: firebase.firestore.FieldValue.serverTimestamp(),
17-
users: [{ name: userName}]
22+
createdBy: userId,
23+
users: [{
24+
userId: userId,
25+
name: userName
26+
}]
1827
});
1928
};
2029

@@ -39,15 +48,18 @@ export const streamGroceryListItems = (groceryListId, observer) => {
3948
.onSnapshot(observer);
4049
};
4150

42-
export const addUserToGroceryList = (userName, groceryListId) => {
51+
export const addUserToGroceryList = (userName, groceryListId, userId) => {
4352
return db.collection('groceryLists')
4453
.doc(groceryListId)
4554
.update({
46-
users: firebase.firestore.FieldValue.arrayUnion({ name: userName})
55+
users: firebase.firestore.FieldValue.arrayUnion({
56+
userId: userId,
57+
name: userName
58+
})
4759
});
4860
};
4961

50-
export const addGroceryListItem = (item, groceryListId) => {
62+
export const addGroceryListItem = (item, groceryListId, userId) => {
5163
return getGroceryListItems(groceryListId)
5264
.then(querySnapshot => querySnapshot.docs)
5365
.then(groceryListItems => groceryListItems.find(groceryListItem => groceryListItem.data().name.toLowerCase() === item.toLowerCase()))
@@ -58,7 +70,8 @@ export const addGroceryListItem = (item, groceryListId) => {
5870
.collection('items')
5971
.add({
6072
name: item,
61-
created: firebase.firestore.FieldValue.serverTimestamp()
73+
created: firebase.firestore.FieldValue.serverTimestamp(),
74+
createdBy: userId
6275
});
6376
}
6477
throw new Error('duplicate-item-error');

0 commit comments

Comments
 (0)