Skip to content

Commit

Permalink
Merge pull request #24 from syeikhanritzmy/dev-redux
Browse files Browse the repository at this point in the history
Redux(auth): use local storage
  • Loading branch information
yusufginanjar committed Sep 30, 2022
2 parents 964cd68 + 50e523b commit d752da8
Show file tree
Hide file tree
Showing 8 changed files with 96 additions and 49 deletions.
10 changes: 5 additions & 5 deletions components/navibar.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,18 +7,17 @@ import Link from 'next/link';
import Image from 'next/image';
import { useSelector, useDispatch } from 'react-redux'
import { login as _login, logout } from '../store/loginSlice';
import { logout as stateLogout } from '../store/authSlice';

export default function Navibar() {
const [user, setUser] = useState(null);
const auth = getAuth();
const router = useRouter();
const [isLogin, setIslogin] = useState("false");
const dispatch = useDispatch();

const login = useSelector(state => {
return state.login.login;
});

useEffect(() => {
setIslogin(localStorage.getItem('isAuthenticated'));
auth.onAuthStateChanged((user) => {
if (user) {
setUser(user);
Expand All @@ -33,6 +32,7 @@ export default function Navibar() {
await signOut(auth);
setUser(null);
dispatch(logout());
dispatch(stateLogout());
router.push('/login');
} catch (error) {
alert(error.message);
Expand Down Expand Up @@ -67,7 +67,7 @@ export default function Navibar() {
<Nav.Link>Top Scores</Nav.Link>
</Link>
</Nav>
{user && login ? (
{user && isLogin == "true" ? (
<Nav className="justify-content-end">
<Link href={"/players/" + user.uid } passHref>
<Nav.Link>Profile</Nav.Link>
Expand Down
2 changes: 2 additions & 0 deletions pages/game/rps.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ export default function Game() {
update(_scoreRef, {
score: new_score,
});
localStorage.setItem('score', new_score);
dispatch(addHistory('win'))
} else if (comScore === 2) {
console.log('you lose');
Expand All @@ -69,6 +70,7 @@ export default function Game() {
update(_scoreRef, {
score: new_score,
});
localStorage.setItem('score', new_score);
dispatch(addHistory('lose'))
}
dispatch(nextRound());
Expand Down
19 changes: 6 additions & 13 deletions pages/games.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -30,19 +30,12 @@ export default function Games() {
router.push("/login");
}

onAuthStateChanged(auth, (user) => {
if (user) {
const db = getDatabase();
const uid = user.uid;
const dataRef = ref(db, "/users/" + uid);
onValue(dataRef, (snapshot) => {
const data = snapshot.val();
setPlayer({
username: data.username,
});
});
}
});
if(localStorage.getItem('username') !== null){
setPlayer({
username: localStorage.getItem('username')
})
}

});
}, []);

Expand Down
12 changes: 11 additions & 1 deletion pages/login.jsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import { useRouter } from 'next/router';
import React, { useEffect, useState } from 'react';
import { signInWithEmailAndPassword, getAuth } from '../firebase/clientApp';
import { signInWithEmailAndPassword, getAuth, ref, getDatabase, onValue } from '../firebase/clientApp';
import { login as stateLogin } from '../store/authSlice';
import { useDispatch } from 'react-redux';
import Swal from 'sweetalert2';
const Toast = Swal.mixin({
toast: true,
Expand All @@ -24,10 +26,18 @@ export default function SignIn() {
const [login, setLogin] = useState(loginState);
const { email, password } = login;

const dispatch = useDispatch();

useEffect(() => {
auth.onAuthStateChanged((user) => {
if (user) {
router.push('games');
const db = getDatabase();
const dataRef = ref(db, '/users/' + user.uid);
onValue(dataRef, (snapshot) => {
const data = snapshot.val();
dispatch(stateLogin(data))
});
}
});
});
Expand Down
50 changes: 20 additions & 30 deletions pages/players/[id].jsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import {useEffect, useState} from "react";
import { getDatabase, ref, onValue, query, orderByChild } from "firebase/database";
import { getAuth, onAuthStateChanged } from "../../firebase/clientApp";

import { useDispatch, useSelector } from "react-redux";
Expand All @@ -22,39 +21,30 @@ export default function Profile() {
const dispatch = useDispatch();

useEffect(() => {
dispatch(processing());
const pathname = window.location.pathname
const getLastItem = thePath => thePath.substring(thePath.lastIndexOf('/') + 1)
const userId = getLastItem(pathname)
setUserId(userId);
dispatch(processing());
const pathname = window.location.pathname
const getLastItem = thePath => thePath.substring(thePath.lastIndexOf('/') + 1)
const userId = getLastItem(pathname)
setUserId(userId);

if(localStorage.getItem('isAuthenticated') === 'true'){
setPlayer({
username: localStorage.getItem('username'),
email: localStorage.getItem('email'),
bio: localStorage.getItem('bio'),
score: localStorage.getItem('score'),
level: Math.ceil(localStorage.getItem('score')/100),
url: localStorage.getItem('url') != 'undefined' ? localStorage.getItem('url') : "https://firebasestorage.googleapis.com/v0/b/fsw22-kelompok1.appspot.com/o/pexels-ron-lach-7848986.jpg?alt=media&token=8a222888-d8f9-4cf6-bc1f-9a744ab0bb5a",
})
};

onAuthStateChanged(auth, (user) => {
if (user) {
if (user) {
const uid = user.uid;
if (uid === userId){ setEnableEdit(true)}
}
});

const db = getDatabase();
const topUserPostsRef = query(ref(db, 'users'),orderByChild('score'));
onValue(topUserPostsRef, (snapshot) => {
const data = snapshot.val();
console.log(data);
});
const dataRef = ref(db, '/users/' + userId);
onValue(dataRef, (snapshot) => {
const data = snapshot.val();
console.log(data.score);
setPlayer({
username: data.username,
email: data.email,
bio: data.bio,
score: data.score,
level: Math.ceil(data.score / 128),
url: data.url ?? "https://firebasestorage.googleapis.com/v0/b/fsw22-kelompok1.appspot.com/o/pexels-ron-lach-7848986.jpg?alt=media&token=8a222888-d8f9-4cf6-bc1f-9a744ab0bb5a",
})
dispatch(success());
});
dispatch(success());
}, [])

return(
Expand Down Expand Up @@ -88,8 +78,8 @@ export default function Profile() {
{enableEdit ?
<Link href={ `/players/edit/${_userId}` }>
{status == 'loading' ?
<button class="btn btn-warning font-weight-bold btn-lg text-dark rounded-0" type="button" disabled>
<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>
<button className="btn btn-warning font-weight-bold btn-lg text-dark rounded-0" type="button" disabled>
<span className="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>
Loading...
</button>
:
Expand Down
4 changes: 4 additions & 0 deletions pages/players/edit/[id].jsx
Original file line number Diff line number Diff line change
Expand Up @@ -84,12 +84,16 @@ export default function ProfileEdit() {
update(ref(db, 'users/' + _userId), {
url: downloadUrl,
});
localStorage.setItem('url', downloadUrl);
}
update(ref(db, 'users/' + _userId), {
username: e.target.username.value,
email: e.target.email.value,
bio: e.target.bio.value,
});
localStorage.setItem('username', e.target.username.value);
localStorage.setItem('email', e.target.email.value);
localStorage.setItem('bio', e.target.bio.value);
await Toast.fire({
icon: 'success',
title: 'Profile Update Successfully',
Expand Down
46 changes: 46 additions & 0 deletions store/authSlice.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import { createSlice } from "@reduxjs/toolkit";

const initialState = {
username: '',
email: '',
bio: '',
score: 0,
url: '',
};

export const authSlice = createSlice({
name: 'auth',
initialState,
reducers: {
login: (state, action) => {
state.username = action.payload.username;
state.email = action.payload.email;
state.bio = action.payload.bio;
state.score = action.payload.score;
state.url = action.payload.url;
localStorage.setItem('isAuthenticated', 'true');
localStorage.setItem('username', action.payload.username);
localStorage.setItem('email', action.payload.email);
localStorage.setItem('bio', action.payload.bio);
localStorage.setItem('score', action.payload.score);
localStorage.setItem('url', action.payload.url);
},
logout: (state) => {
state.username = '';
state.email = '';
state.bio = '';
state.score = 0;
state.url = '';
localStorage.setItem('isAuthenticated', 'false');
localStorage.removeItem("username");
localStorage.removeItem("email");
localStorage.removeItem("bio");
localStorage.removeItem("score");
localStorage.removeItem("url");
}
}
});

export const { login, logout } = authSlice.actions;

export const authReducer = authSlice.reducer;
2 changes: 2 additions & 0 deletions store/index.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { configureStore } from '@reduxjs/toolkit';
import { statusReducer } from './statusSlice';
import { loginReducer } from './loginSlice';
import { authReducer } from './authSlice';
import { gameReducer } from './gameSlice';
import { gamesReducer } from './gamesSlice';
import { createWrapper } from 'next-redux-wrapper';
Expand All @@ -9,6 +10,7 @@ export const store = configureStore({
reducer: {
status: statusReducer,
login: loginReducer,
auth: authReducer,
game: gameReducer,
games: gamesReducer
},});
Expand Down

0 comments on commit d752da8

Please sign in to comment.