Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Updated code to modern Firebase v9 #27

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 25 additions & 27 deletions src/App.js
Original file line number Diff line number Diff line change
@@ -1,43 +1,41 @@
import React from 'react';
import { Switch, Route } from 'react-router-dom';
import React, { Component } from "react";
import { Switch, Route } from "react-router-dom";

import './App.css';
import HomePage from "./pages/homepage/homepage.component";
import Shop from "./pages/shop/shop.component";
import Header from "./components/header/header.component";
import SignInAndSignUpPage from "./pages/sign-in-and-sign-up/sign-in-and-sign-up.component";
import { userAuth, createUserProfileDocument } from "./firebase/firebase.utils";

import HomePage from './pages/homepage/homepage.component';
import ShopPage from './pages/shop/shop.component';
import SignInAndSignUpPage from './pages/sign-in-and-sign-up/sign-in-and-sign-up.component';
import Header from './components/header/header.component';
import { auth, createUserProfileDocument } from './firebase/firebase.utils';
import "./App.scss";

class App extends React.Component {
constructor() {
super();

this.state = {
currentUser: null
};
}
class App extends Component {
state = {
currentUser: null,
};

unsubscribeFromAuth = null;

componentDidMount() {
this.unsubscribeFromAuth = auth.onAuthStateChanged(async userAuth => {
this.unsubscribeFromAuth = userAuth.onAuthStateChanged(async (userAuth) => {
if (userAuth) {
const userRef = await createUserProfileDocument(userAuth);
const { userRef, onSnapshot } = await createUserProfileDocument(
userAuth
);

userRef.onSnapshot(snapShot => {
onSnapshot(userRef, (snapshot) => {
this.setState({
currentUser: {
id: snapShot.id,
...snapShot.data()
}
id: snapshot.id,
...snapshot.data(),
},
});

console.log(this.state);
});
} else {
this.setState({ currentUser: userAuth });
}

this.setState({ currentUser: userAuth });
});
}

Expand All @@ -50,9 +48,9 @@ class App extends React.Component {
<div>
<Header currentUser={this.state.currentUser} />
<Switch>
<Route exact path='/' component={HomePage} />
<Route path='/shop' component={ShopPage} />
<Route path='/signin' component={SignInAndSignUpPage} />
<Route exact path="/" component={HomePage} />
<Route path="/shop" component={Shop} />
<Route path="/signin" component={SignInAndSignUpPage} />
</Switch>
</div>
);
Expand Down
89 changes: 42 additions & 47 deletions src/components/sign-up/sign-up.component.jsx
Original file line number Diff line number Diff line change
@@ -1,26 +1,24 @@
import React from 'react';
import React, { Component } from "react";
import FormInput from "../form-input/form-input.component";
import CustomButton from "../custom-button/custom-button.component";
import {
userAuth,
createUserProfileDocument,
createAccount,
} from "../../firebase/firebase.utils";

import FormInput from '../form-input/form-input.component';
import CustomButton from '../custom-button/custom-button.component';
import "./sign-up.styles.scss";

import { auth, createUserProfileDocument } from '../../firebase/firebase.utils';

import './sign-up.styles.scss';

class SignUp extends React.Component {
constructor() {
super();

this.state = {
displayName: '',
email: '',
password: '',
confirmPassword: ''
};
}
class SignUp extends Component {
state = {
displayName: "",
email: "",
password: "",
confirmPassword: "",
};

handleSubmit = async event => {
event.preventDefault();
handleSubmit = async (e) => {
e.preventDefault();

const { displayName, email, password, confirmPassword } = this.state;

Expand All @@ -30,25 +28,22 @@ class SignUp extends React.Component {
}

try {
const { user } = await auth.createUserWithEmailAndPassword(
email,
password
);
const { user } = await createAccount(userAuth, email, password);

await createUserProfileDocument(user, { displayName });

this.setState({
displayName: '',
email: '',
password: '',
confirmPassword: ''
displayName: "",
email: "",
password: "",
confirmPassword: "",
});
} catch (error) {
console.error(error);
} catch (err) {
console.error(err);
}
};

handleChange = event => {
handleChange = (event) => {
const { name, value } = event.target;

this.setState({ [name]: value });
Expand All @@ -57,43 +52,43 @@ class SignUp extends React.Component {
render() {
const { displayName, email, password, confirmPassword } = this.state;
return (
<div className='sign-up'>
<h2 className='title'>I do not have a account</h2>
<div className="sign-up">
<h2 className="title">I do not have an account</h2>
<span>Sign up with your email and password</span>
<form className='sign-up-form' onSubmit={this.handleSubmit}>
<form className="sign-up-form" onSubmit={this.handleSubmit}>
<FormInput
type='text'
name='displayName'
type="text"
name="displayName"
value={displayName}
onChange={this.handleChange}
label='Display Name'
label="Display Name"
required
/>
<FormInput
type='email'
name='email'
type="email"
name="email"
value={email}
onChange={this.handleChange}
label='Email'
label="Email"
required
/>
<FormInput
type='password'
name='password'
type="password"
name="password"
value={password}
onChange={this.handleChange}
label='Password'
label="Password"
required
/>
<FormInput
type='password'
name='confirmPassword'
type="password"
name="confirmPassword"
value={confirmPassword}
onChange={this.handleChange}
label='Confirm Password'
label="Confirm Password"
required
/>
<CustomButton type='submit'>SIGN UP</CustomButton>
<CustomButton type="submit">SIGN UP</CustomButton>
</form>
</div>
);
Expand Down
73 changes: 42 additions & 31 deletions src/firebase/firebase.utils.js
Original file line number Diff line number Diff line change
@@ -1,49 +1,60 @@
import firebase from 'firebase/app';
import 'firebase/firestore';
import 'firebase/auth';
import { initializeApp } from "firebase/app";
import {
getAuth,
signInWithPopup,
GoogleAuthProvider,
createUserWithEmailAndPassword,
} from "firebase/auth";
//prettier-ignore
import { getFirestore, doc, getDoc, setDoc, onSnapshot } from "firebase/firestore";

const config = {
apiKey: 'AIzaSyCdHT-AYHXjF7wOrfAchX4PIm3cSj5tn14',
authDomain: 'crwn-db.firebaseapp.com',
databaseURL: 'https://crwn-db.firebaseio.com',
projectId: 'crwn-db',
storageBucket: 'crwn-db.appspot.com',
messagingSenderId: '850995411664',
appId: '1:850995411664:web:7ddc01d597846f65'
apiKey: "AIzaSyCdHT-AYHXjF7wOrfAchX4PIm3cSj5tn14",
authDomain: "crwn-db.firebaseapp.com",
databaseURL: "https://crwn-db.firebaseio.com",
projectId: "crwn-db",
storageBucket: "crwn-db.appspot.com",
messagingSenderId: "850995411664",
appId: "1:850995411664:web:7ddc01d597846f65",
};

firebase.initializeApp(config);
const app = initializeApp(config);
const db = getFirestore(app);

export const userAuth = getAuth(app);
export const firestore = getFirestore(app);
export const createAccount = createUserWithEmailAndPassword;

const provider = new GoogleAuthProvider();
provider.setCustomParameters({ prompt: "select_account" });

export const signInWithGoogle = () =>
signInWithPopup(userAuth, provider).catch((error) => console.log(error));

export const createUserProfileDocument = async (userAuth, additionalData) => {
if (!userAuth) return;

const userRef = firestore.doc(`users/${userAuth.uid}`);

const snapShot = await userRef.get();
const userRef = doc(db, "users", `${userAuth.uid}`);
const snapShot = await getDoc(userRef);

if (!snapShot.exists) {
if (!snapShot.exists()) {
const { displayName, email } = userAuth;
const createdAt = new Date();
const createAt = new Date();

try {
await userRef.set({
await setDoc(userRef, {
displayName,
email,
createdAt,
...additionalData
createAt,
...additionalData,
});
} catch (error) {
console.log('error creating user', error.message);
} catch (err) {
console.log("error creating user", err.message);
}
}

return userRef;
return {
userRef,
onSnapshot,
};
};

export const auth = firebase.auth();
export const firestore = firebase.firestore();

const provider = new firebase.auth.GoogleAuthProvider();
provider.setCustomParameters({ prompt: 'select_account' });
export const signInWithGoogle = () => auth.signInWithPopup(provider);

export default firebase;