Skip to content

Commit

Permalink
redux hooks
Browse files Browse the repository at this point in the history
  • Loading branch information
FacuEM committed Feb 11, 2021
1 parent 10b634e commit 2cc9334
Show file tree
Hide file tree
Showing 12 changed files with 208 additions and 71 deletions.
5 changes: 5 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
"react-scripts": "4.0.2",
"redux": "^4.0.5",
"redux-logger": "^3.0.6",
"redux-thunk": "^2.3.0",
"web-vitals": "^1.1.0"
},
"scripts": {
Expand Down
29 changes: 12 additions & 17 deletions src/App.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { Switch, Route, Redirect } from "react-router-dom";
import { Switch, Route } from "react-router-dom";
import React, { useEffect } from "react";
import { auth, handleUserProfile } from "./firebase/utils";
import { connect } from "react-redux";
import { useDispatch } from "react-redux";
import { setCurrentUser } from "./redux/User/user.actions";
import "./default.scss";

Expand All @@ -17,20 +17,22 @@ import Login from "./pages/Login";
import Recovery from "./pages/Recovery";
import Dashboard from "./pages/Dashboard";

const App = (props) => {
const { setCurrentUser, currentUser } = props;
const App = () => {
const dispatch = useDispatch();
useEffect(() => {
const authListener = auth.onAuthStateChanged(async (userAuth) => {
if (userAuth) {
const userRef = await handleUserProfile(userAuth);
userRef.onSnapshot((snapshot) => {
setCurrentUser({
id: snapshot.id,
...snapshot.data(),
});
dispatch(
setCurrentUser({
id: snapshot.id,
...snapshot.data(),
})
);
});
}
setCurrentUser(userAuth);
dispatch(setCurrentUser(userAuth));
});

return () => {
Expand Down Expand Up @@ -89,11 +91,4 @@ const App = (props) => {
);
};

const mapStateToProps = ({ user }) => ({
currentUser: user.currentUser,
});
const mapDispatchToProps = (dispatch) => ({
setCurrentUser: (user) => dispatch(setCurrentUser(user)),
});

export default connect(mapStateToProps, mapDispatchToProps)(App);
export default App;
47 changes: 29 additions & 18 deletions src/components/EmailPassword/index.js
Original file line number Diff line number Diff line change
@@ -1,32 +1,43 @@
import React, { useState } from "react";
import React, { useState, useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import {
resetPassword,
resetAllAuthForms,
} from "./../../redux/User/user.actions";
import { useHistory } from "react-router-dom";
import "./styles.scss";
import AuthWrapper from "./../AuthWrapper";
import FormInput from "./../forms/FormInput";
import Button from "./../forms/Button";
import { auth } from "./../../firebase/utils";

const EmailPassword = (props) => {
const EmailPassword = () => {
let history = useHistory();
const dispatch = useDispatch();
const [email, setEmail] = useState("");
const [errors, setErrors] = useState([]);
const handleSubmit = async (e) => {
e.preventDefault();
const resetPasswordSuccess = useSelector(
(state) => state.user.resetPasswordSuccess
);
const resetPasswordError = useSelector(
(state) => state.user.resetPasswordError
);

try {
const config = {
url: "http://localhost:3000/login",
};
await auth
.sendPasswordResetEmail(email, config)
.then(() => history.push("/login"))
.catch(() => {
const err = ["Email not found. Please try again."];
setErrors(err);
});
} catch (err) {
console.log(err);
useEffect(() => {
if (resetPasswordSuccess) {
dispatch(resetAllAuthForms());
history.push("/login");
}
}, [resetPasswordSuccess]);

useEffect(() => {
if (Array.isArray(resetPasswordError) && resetPasswordError.length > 0) {
setErrors(resetPasswordError);
}
}, [resetPasswordError]);

const handleSubmit = (e) => {
e.preventDefault();
dispatch(resetPassword({ email }));
};

const configAuthWrapper = {
Expand Down
32 changes: 22 additions & 10 deletions src/components/SignIn/index.js
Original file line number Diff line number Diff line change
@@ -1,27 +1,39 @@
import React, { useState } from "react";
import React, { useState, useEffect } from "react";
import "./styles.scss";
import { signInWitGoogle, auth } from "./../../firebase/utils";
import { Link, useHistory } from "react-router-dom";
import { useDispatch, useSelector } from "react-redux";
import {
signInUser,
signInWithGoogle,
resetAllAuthForms,
} from "./../../redux/User/user.actions";
import FormInput from "./../forms/FormInput";
import Button from "./../forms/Button";
import AuthWrapper from "./../AuthWrapper";

const SignIn = (props) => {
const history = useHistory();
const dispatch = useDispatch();
const signInSuccess = useSelector((state) => state.user.signInSuccess);
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");

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

try {
await auth.signInWithEmailAndPassword(email, password);
useEffect(() => {
if (signInSuccess) {
setEmail("");
setPassword("");
dispatch(resetAllAuthForms());
history.push("/");
} catch (error) {
console.log(error);
}
}, [signInSuccess]);

const handleSubmit = (e) => {
e.preventDefault();
dispatch(signInUser({ email, password }));
};

const handleGoogleSignIn = () => {
dispatch(signInWithGoogle());
};

const configAuthWrapper = {
Expand Down Expand Up @@ -50,7 +62,7 @@ const SignIn = (props) => {

<div className="socialSignin">
<div className="row">
<Button onClick={signInWitGoogle}>Sign in with Google</Button>
<Button onClick={handleGoogleSignIn}>Sign in with Google</Button>
</div>
</div>
<div className="links">
Expand Down
35 changes: 18 additions & 17 deletions src/components/Signup/index.js
Original file line number Diff line number Diff line change
@@ -1,43 +1,44 @@
import React, { useState } from "react";
import React, { useState, useEffect } from "react";
import FormInput from "./../forms/FormInput";
import Button from "./../forms/Button";
import AuthWrapper from "./../AuthWrapper";
import "./styles.scss";
import { auth, handleUserProfile } from "./../../firebase/utils";
import { useHistory } from "react-router-dom";
import { useDispatch, useSelector } from "react-redux";
import { signUpUser, resetAllAuthForms } from "./../../redux/User/user.actions";

const Signup = (props) => {
const history = useHistory();
const dispatch = useDispatch();
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [displayName, setDisplayName] = useState("");
const [confirmPassword, setComfirmPassword] = useState("");
const [errors, setErrors] = useState([]);
const signUpSuccess = useSelector((state) => state.user.signUpSuccess);
const signUpError = useSelector((state) => state.user.signUpError);

const handleFormSubmit = async (e) => {
e.preventDefault();

if (password !== confirmPassword) {
const err = ["Password Don't match"];
setErrors(err);
return;
useEffect(() => {
if (Array.isArray(signUpError) && signUpError.length > 0) {
setErrors(signUpError);
}
}, [signUpError]);

try {
const { user } = await auth.createUserWithEmailAndPassword(
email,
password
);
await handleUserProfile(user, { displayName });
useEffect(() => {
if (signUpSuccess) {
setEmail("");
setPassword("");
setDisplayName("");
setComfirmPassword("");
setErrors([]);
dispatch(resetAllAuthForms());
history.push("/");
} catch (error) {
console.log(error);
}
}, [signUpSuccess]);

const handleFormSubmit = (e) => {
e.preventDefault();
dispatch(signUpUser({ displayName, email, password, confirmPassword }));
};

const configAuthWrapper = {
Expand Down
8 changes: 2 additions & 6 deletions src/customHooks/useAuth.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,8 @@ import { useSelector } from "react-redux";
import { useEffect } from "react";
import { useHistory } from "react-router-dom";

const mapState = ({ user }) => ({
currentUser: user.currentUser,
});

const useAuth = (props) => {
const { currentUser } = useSelector(mapState);
const useAuth = () => {
const currentUser = useSelector((state) => state.user.currentUser);
const history = useHistory();
useEffect(() => {
if (!currentUser) {
Expand Down
3 changes: 1 addition & 2 deletions src/firebase/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,8 @@ firebase.initializeApp(firebaseConfig);
export const auth = firebase.auth();
export const firestore = firebase.firestore();

const GoogleProvider = new firebase.auth.GoogleAuthProvider();
export const GoogleProvider = new firebase.auth.GoogleAuthProvider();
GoogleProvider.setCustomParameters({ prompt: "select_account" });
export const signInWitGoogle = () => auth.signInWithPopup(GoogleProvider);

export const handleUserProfile = async (userAuth, additionalData) => {
if (!userAuth) return;
Expand Down
86 changes: 86 additions & 0 deletions src/redux/User/user.actions.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,92 @@
import userTypes from "./user.types";
import {
auth,
handleUserProfile,
GoogleProvider,
} from "./../../firebase/utils";

export const setCurrentUser = (user) => ({
type: userTypes.SET_CURRENT_USER,
payload: user,
});

export const signInUser = ({ email, password }) => async (dispatch) => {
try {
await auth.signInWithEmailAndPassword(email, password);
dispatch({
type: userTypes.SIGN_IN_SUCCESS,
payload: true,
});
} catch (error) {
console.log(error);
}
};

export const signUpUser = ({
displayName,
email,
password,
confirmPassword,
}) => async (dispatch) => {
if (password !== confirmPassword) {
const err = ["Password Don't match"];
dispatch({
type: userTypes.SIGN_UP_ERROR,
payload: err,
});
return;
}

try {
const { user } = await auth.createUserWithEmailAndPassword(email, password);
await handleUserProfile(user, { displayName });
dispatch({
type: userTypes.SIGN_UP_SUCCESS,
payload: true,
});
} catch (error) {
console.log(error);
}
};

export const resetPassword = ({ email }) => async (dispatch) => {
const config = {
url: "http://localhost:3000/login",
};
try {
await auth
.sendPasswordResetEmail(email, config)
.then(() => {
dispatch({
type: userTypes.RESET_PASSWORD_SUCCESS,
payload: true,
});
})
.catch(() => {
const err = ["Email not found. Please try again."];
dispatch({
type: userTypes.RESET_PASSWORD_ERROR,
payload: err,
});
});
} catch (err) {
console.log(err);
}
};

export const signInWithGoogle = () => async (dispatch) => {
try {
await auth.signInWithPopup(GoogleProvider).then(() => {
dispatch({
type: userTypes.SIGN_IN_SUCCESS,
payload: true,
});
});
} catch (err) {
console.log(err);
}
};

export const resetAllAuthForms = () => ({
type: userTypes.RESET_AUTH_FORMS,
});
Loading

0 comments on commit 2cc9334

Please sign in to comment.