Skip to content

Commit

Permalink
added storing our collection data in firestore
Browse files Browse the repository at this point in the history
  • Loading branch information
LoukrichiFouad97 committed Jul 18, 2020
1 parent 96975e7 commit 3fb7d19
Show file tree
Hide file tree
Showing 2 changed files with 68 additions and 32 deletions.
26 changes: 19 additions & 7 deletions src/App.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,33 +12,46 @@ import Header from "./components/header/header";
import CheckoutPage from "./pages/checkout/checkout";

import { auth } from "./firebase/firebase-utils";
import { createUserProfileDocument } from "./firebase/firebase-utils";
import {
createUserProfileDocument,
} from "./firebase/firebase-utils";
import { setCurrentUser } from "./redux/user/user-actions";
import { selectCurrentUser } from "./redux/user/user-selectors";

class App extends Component {
unsubscribeFromAuth = null;

/** componentDidMount function
* [1] keep track of the authenticated user status using: onAuthStateChanged(authenticated user)
* [2] check if user is authenticated
* [3] store the user in firebase && get back his documentReference using: createUserProfileDocument(user)
* [4] setup a listener on user snapshot that stores the user in the state
*/

// open connection to watch user auth changes
componentDidMount() {
const { setCurrentUser } = this.props;

this.unsubscribeFromAuth = auth.onAuthStateChanged(async (user) => {
// if user signed in
if (user) {
// get the user obj
// get the user documentReference. after, storing it in firestore.
const userRef = await createUserProfileDocument(user);

// after db updates with new user
userRef.onSnapshot((snapshot) => {
// trigger redux action creator func && set snapshot data as a payload
setCurrentUser({
id: snapshot.id,
...snapshot.data(),
});
console.log(this.state);
});
} else {
setCurrentUser({ user });
// addCollectionAndDocuments(
// "collection",
// collectionsArray.map(({ title, items }) => ({ title, items }))
// );
}
});
}
Expand All @@ -59,25 +72,24 @@ class App extends Component {
<Route exact path="/contact" component={() => <h1>contact</h1>} />
<Route exact path="/checkout" component={CheckoutPage} />
<Route
exact
path="/signin"
render={() =>
currentUser ? <Redirect to="/" /> : <SignInAndSignUp />
}
/>
<Route component={() => <h1>404 Not Found</h1>} />
</Switch>
</div>
);
}
}

// access to state
// Access the current user from the state
const mapStateToProps = createStructuredSelector({
currentUser: selectCurrentUser,
// collectionsArray: selectCollectionForPreview,
});

// set state
// Store the user in the state
const mapDispatchToProps = (dispatch) => ({
setCurrentUser: (user) => dispatch(setCurrentUser(user)),
});
Expand Down
74 changes: 49 additions & 25 deletions src/firebase/firebase-utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,8 @@ export const firestore = firebase.firestore();
* [1] get the user && any additional data parameters
* [2] check if user is authenticated or not
* [3] get the user documentReference && get userSnapshot
* [4]
* [4] check if snapshot exists or not
*
*
*/

Expand All @@ -34,38 +35,61 @@ export const createUserProfileDocument = async (
// Request user document reference object
const userRef = firestore.doc(`users/${userAuth.uid}`);

console.log(userRef);
// get user document snapshot obj using user document reference
const snapshot = await userRef.get();
console.log(snapshot);

// // if user is not registered
// if (!snapshot.exists) {
// // Get displayName and email from the authenticated user
// const { displayName, email } = userAuth;
// const createdAt = new Date();

// // Create user document && account
// try {
// await userRef.set({
// displayName,
// email,
// createdAt,
// ...additionalData,
// });
// } catch (err) {
// console.log("Error registering user", err.message);
// }
// }

// return userRef;

// if user is not registered
if (!snapshot.exists) {
// Get displayName and email from the authenticated user
const { displayName, email } = userAuth;
const createdAt = new Date();

// Create user document && account
try {
await userRef.set({
displayName,
email,
createdAt,
...additionalData,
});
} catch (err) {
console.log("Error registering user", err.message);
}
}

return userRef;
};

/** addCollectionAndDocuments func
* [1] get the collection key && the document to be added
* [2] get the reference of the collection
* [3] make sure to use firestore.batch() to avoid half fail errors (all success || all fail)
* [4] loop through the documents to add && create documentReferences for each document
* [5] bind each document with documentReference using batch.set() func
* [6] don't forget to commit batches
*/

export const addCollectionAndDocuments = async (
collectionKey,
documentsToAdd
) => {
const collectionRef = firestore.collection(collectionKey);
console.log(collectionRef);

const batch = firestore.batch();
documentsToAdd.forEach((document) => {
const newDocRef = collectionRef.doc();
batch.set(newDocRef, document);
});

return await batch.commit();
};

// Use google as an authentication provider
const googleProvider = new firebase.auth.GoogleAuthProvider();

// trigger auth pop up
googleProvider.setCustomParameters({ prompet: "select_account" });
googleProvider.setCustomParameters({ prompt: "select_account" });

// Use pop-up as a way of authenticating
export const signInWithGoogle = () => auth.signInWithPopup(googleProvider);
Expand Down

0 comments on commit 3fb7d19

Please sign in to comment.