Fakultas Ilmu Komputer UI

Commit 9ff69956 authored by Ahmad Izzudin Alifyandra's avatar Ahmad Izzudin Alifyandra
Browse files

Refactor: Add auth conditional navigation rendering

parent d4dc9533
import { TypedUseSelectorHook, useDispatch, useSelector } from "react-redux";
import type { RootState, AppDispatch } from "../redux/store";
// Use throughout your app instead of plain `useDispatch` and `useSelector`
export const useAppDispatch = () => useDispatch<AppDispatch>();
export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector;
......@@ -16,17 +16,17 @@ const AuthStackNavigator = () => {
<AuthStack.Screen
name="onboarding"
component={OnBoardingScreen}
options={{ headerShown: false }}
options={{ title: "" }}
/>
<AuthStack.Screen
name="Login"
component={LoginScreen}
options={{ headerShown: false }}
options={{ title: "" }}
/>
<AuthStack.Screen
name="landing"
component={LandingScreen}
options={{ headerShown: false }}
options={{ title: "" }}
/>
<AuthStack.Screen
name="RegisterGoogle"
......
import * as React from "react";
import React, { useEffect, useState } from "react";
import { createNativeStackNavigator } from "@react-navigation/native-stack";
import BottomTabNavigator from "./BottomTabNavigator";
import { RootStackParamList } from "../types/navigation";
import AuthStackNavigator from "./AuthStackNavigator";
import SuccessChangePasswordScreen from "../screens/SuccessChangePasswordScreen";
import { IUser } from "../types/firebase/User";
import { RootState } from "../redux/store";
import { useAppDispatch, useAppSelector } from "../hooks/reduxHooks";
import { getCurrentAuthUser } from "../service/firebase/auth";
import { getUser } from "../redux/user/actions";
import OnBoardingScreen from "../screens/auth/OnBoardingScreen";
import LandingScreen from "../screens/auth/LandingScreen";
import { useDispatch } from "react-redux";
import firebase from "firebase";
import { Alert } from "react-native";
/**
* A root stack navigator is often used for displaying modals on top of all other content.
......@@ -12,21 +22,67 @@ import SuccessChangePasswordScreen from "../screens/SuccessChangePasswordScreen"
const RootStack = createNativeStackNavigator<RootStackParamList>();
const RootNavigator = () => {
return (
const user: IUser = useAppSelector((state) => state.user);
const [isLoading, setIsLoading] = useState(true);
const dispatch = useAppDispatch();
useEffect(() => {
const unsubscribeAuth = firebase
.auth()
.onAuthStateChanged((currentUser) => {
try {
// await (authenticatedUser ? setUser(authenticatedUser) : setUser(null));
// setIsLoading(false);
if (currentUser) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-call
dispatch(getUser(currentUser.uid)).then(setIsLoading(false));
} else {
setIsLoading(false);
}
} catch (error) {
console.log(error);
Alert.alert("Error", error);
}
});
// unsubscribe auth listener on unmount
return unsubscribeAuth;
// const currentUser = getCurrentAuthUser();
// if (currentUser) {
// // eslint-disable-next-line @typescript-eslint/no-unsafe-call
// dispatch(getUser(currentUser.uid)).then(setIsLoading(false));
// } else {
// setIsLoading(false);
// }
}, []);
return !isLoading ? (
<RootStack.Navigator>
{user.id === "" && (
<RootStack.Screen
name="Auth"
component={AuthStackNavigator}
options={{ headerShown: false }}
/>
)}
{user.id !== "" && (
<RootStack.Screen
name="MainTab"
component={BottomTabNavigator}
options={{ headerShown: false }}
/>
)}
<RootStack.Screen
name="Auth"
component={AuthStackNavigator}
options={{ headerShown: false }}
/>
<RootStack.Screen
name="MainTab"
component={BottomTabNavigator}
name="SuccessChangePassword"
component={SuccessChangePasswordScreen}
options={{ headerShown: false }}
/>
</RootStack.Navigator>
) : (
<RootStack.Navigator>
<RootStack.Screen
name="SuccessChangePassword"
component={SuccessChangePasswordScreen}
name="RootLoading"
component={LandingScreen}
options={{ headerShown: false }}
/>
</RootStack.Navigator>
......
import { combineReducers, createStore, applyMiddleware } from "redux";
import { configureStore } from "@reduxjs/toolkit";
import userReducer from "./user/reducer";
import thunkMiddleware from "redux-thunk";
import thunk from "redux-thunk";
const rootReducer = combineReducers({
user: userReducer,
});
// const rootReducer = combineReducers({
// user: userReducer,
// });
const middleware = applyMiddleware(thunkMiddleware);
const store = createStore(rootReducer, middleware);
// const middleware = applyMiddleware(thunkMiddleware);
// const store = createStore(rootReducer, middleware);
const store = configureStore({
reducer: {
user: userReducer,
},
middleware: [thunk],
});
export type RootState = ReturnType<typeof rootReducer>;
export type RootState = ReturnType<typeof store.getState>;
export type AppDispatch = typeof store.dispatch;
export default store;
import firebase from "firebase/app";
import { Dispatch } from "react-redux/node_modules/@types/react";
import * as userService from "../../service/firestore/user";
import { IUser } from "../../types/firebase/User";
import * as authService from "../../service/firebase/auth";
const getUser = (uid: string) => {
export const getUser = (uid: string) => {
return async (dispatch: Dispatch<any>) => {
try {
const user = await userService.getUser(uid);
dispatch({ type: "LOGIN", payload: { ...user.data(), id: user.id } });
return dispatch({
type: "LOGIN",
payload: { ...user.data(), id: user.id },
});
} catch (e) {
console.log(e);
}
......
......@@ -3,7 +3,7 @@ import { IUser } from "../../types/firebase/User";
const initialState: IUser = {
id: "",
firstName: "james",
firstName: "",
lastName: "",
phone: "",
email: "",
......@@ -13,6 +13,7 @@ const initialState: IUser = {
const userReducer = (state = initialState, action: AnyAction): IUser => {
switch (action.type) {
case "LOGIN":
console.log("login");
return action.payload as IUser;
case "LOGOUT":
return initialState;
......
......@@ -82,9 +82,7 @@ const LoginScreen = ({ navigation }: RootTabScreenProps<"TabOne">) => {
Belum Punya akun?
<Text
style={styles.register}
onPress={() =>
nav.navigate("Auth", { screen: "ForgotPasswordInput" })
}
onPress={() => nav.navigate("Auth", { screen: "RegisterScreen" })}
>
Daftar disini
</Text>
......
......@@ -10,11 +10,9 @@ import { RootTabScreenProps } from "../../types/navigation";
import Spacer from "../../components/Spacer/Spacer";
import { pickImage, uploadImgToFirebase } from "../../helpers/images";
import { ImageInfo } from "expo-image-picker/build/ImagePicker.types";
import { useDispatch } from "react-redux";
import { setProfilePic } from "../../redux/user/actions";
import { useSelector } from "react-redux";
import { RootState } from "../../redux/store";
import { IUser } from "../../types/firebase/User";
import { useAppDispatch, useAppSelector } from "../../hooks/reduxHooks";
export default function AccountSettingsScreen({
navigation,
......@@ -26,8 +24,8 @@ export default function AccountSettingsScreen({
const [bisnis, setBisnis] = useState("");
const nav = useNavigation();
const [isLoading, setIsLoading] = useState(false);
const dispatch = useDispatch();
const user: IUser = useSelector((state: RootState) => state.user);
const dispatch = useAppDispatch();
const user: IUser = useAppSelector((state) => state.user);
const handlePickImage = () => {
setIsLoading(true);
pickImage().then((res) => {
......
......@@ -4,6 +4,10 @@ export const createCredential = (email: string, password: string) => {
return firebase.auth.EmailAuthProvider.credential(email, password);
};
export const getCurrentAuthUser = () => {
return firebase.auth().currentUser;
};
export const loginUser = async (credential: firebase.auth.AuthCredential) => {
return await firebase.auth().signInWithCredential(credential);
};
......
import firebase from "firebase/app";
import { useSelector } from "react-redux";
import { RootState } from "../../redux/store";
import userReducer from "../../redux/user/reducer";
import { IUser } from "../../types/firebase/User";
export const addProfilePic = async (url: string, userId: string) => {
const db = firebase.firestore();
......
......@@ -2690,6 +2690,16 @@
dependencies:
nanoid "^3.1.23"
"@reduxjs/toolkit@^1.6.1":
version "1.6.1"
resolved "https://registry.yarnpkg.com/@reduxjs/toolkit/-/toolkit-1.6.1.tgz#7bc83b47352a663bf28db01e79d17ba54b98ade9"
integrity sha512-pa3nqclCJaZPAyBhruQtiRwtTjottRrVJqziVZcWzI73i6L3miLTtUyWfauwv08HWtiXLx1xGyGt+yLFfW/d0A==
dependencies:
immer "^9.0.1"
redux "^4.1.0"
redux-thunk "^2.3.0"
reselect "^4.0.0"
"@sinonjs/commons@^1.7.0":
version "1.8.3"
resolved "https://registry.yarnpkg.com/@sinonjs/commons/-/commons-1.8.3.tgz"
......@@ -5938,6 +5948,11 @@ image-size@^0.6.0:
resolved "https://registry.yarnpkg.com/image-size/-/image-size-0.6.3.tgz"
integrity sha512-47xSUiQioGaB96nqtp5/q55m0aBQSQdyIloMOc/x+QVTDZLNmXE892IIDrJ0hM1A5vcNUDD5tDffkSP5lCaIIA==
immer@^9.0.1:
version "9.0.6"
resolved "https://registry.yarnpkg.com/immer/-/immer-9.0.6.tgz#7a96bf2674d06c8143e327cbf73539388ddf1a73"
integrity sha512-G95ivKpy+EvVAnAab4fVa4YGYn24J1SpEktnJX7JJ45Bd7xqME/SCplFzYFmTbrkwZbQ4xJK1xMTUYBkN6pWsQ==
import-fresh@^2.0.0:
version "2.0.0"
resolved "https://registry.yarnpkg.com/import-fresh/-/import-fresh-2.0.0.tgz"
......@@ -9329,7 +9344,7 @@ redux-thunk@^2.3.0:
resolved "https://registry.yarnpkg.com/redux-thunk/-/redux-thunk-2.3.0.tgz#51c2c19a185ed5187aaa9a2d08b666d0d6467622"
integrity sha512-km6dclyFnmcvxhAcrQV2AkZmPQjzPDjgVlQtR0EQjxZPyJ0BnMf3in1ryuR8A2qU0HldVRfxYXbFSKlI3N7Slw==
redux@^4.0.0, redux@^4.1.1:
redux@^4.0.0, redux@^4.1.0, redux@^4.1.1:
version "4.1.1"
resolved "https://registry.yarnpkg.com/redux/-/redux-4.1.1.tgz#76f1c439bb42043f985fbd9bf21990e60bd67f47"
integrity sha512-hZQZdDEM25UY2P493kPYuKqviVwZ58lEmGQNeQ+gXa+U0gYPUBf7NKYazbe3m+bs/DzM/ahN12DbF+NG8i0CWw==
......@@ -9487,6 +9502,11 @@ reselect@^3.0.1:
resolved "https://registry.yarnpkg.com/reselect/-/reselect-3.0.1.tgz"
integrity sha1-79qpjqdFEyTQkrKyFjpqHXqaIUc=
reselect@^4.0.0:
version "4.0.0"
resolved "https://registry.yarnpkg.com/reselect/-/reselect-4.0.0.tgz#f2529830e5d3d0e021408b246a206ef4ea4437f7"
integrity sha512-qUgANli03jjAyGlnbYVAV5vvnOmJnODyABz51RdBN7M4WaVu8mecZWgyQNkG8Yqe3KRGRt0l4K4B3XVEULC4CA==
resolve-cwd@^3.0.0:
version "3.0.0"
resolved "https://registry.yarnpkg.com/resolve-cwd/-/resolve-cwd-3.0.0.tgz"
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment