Skip to content

Commit

Permalink
fix(*): fix infinite render
Browse files Browse the repository at this point in the history
navbar: only set the token, and refresh the state if the token nor data doesn't exist
session_store: add failed state as condition to allow request if previous state isn't failed
login: remove setToken, and push router

Signed-off-by: hanifdwyputras <hanifdwyputrasembiring@gmail.com>
  • Loading branch information
hansputera committed Jun 3, 2023
1 parent 36fe111 commit eda089f
Show file tree
Hide file tree
Showing 6 changed files with 96 additions and 11 deletions.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
"@types/react-dom": "18.2.4",
"autoprefixer": "10.4.14",
"daisyui": "^3.0.1",
"echarts-for-react": "^3.0.2",
"eslint": "8.41.0",
"eslint-config-next": "13.4.4",
"formik": "^2.4.1",
Expand Down
36 changes: 36 additions & 0 deletions pnpm-lock.yaml

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

25 changes: 24 additions & 1 deletion src/app/me/page.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,34 @@
'use client';
import React from 'react'
import { useSessionStore } from '@/contexts/sessionContext'
import Image from 'next/image'
// import Image from 'next/image'
import Link from 'next/link'

type StatsJson = {
archives: {
all: number;
complete: number;
speciifed: Record<string, number>;
daily: {
todayCount: number;
lastWeek: number;
};
};
}

export default function MePage() {
const session = useSessionStore();
const [data, setData] = React.useState();

React.useEffect(() => {
if (session.token)
fetch('/api/stats', {
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${session.token}`,
}
}).then(r => r.json()).then(setData);
}, [session?.token]);
return (
<main>
<div className="hero min-h-screen bg-base-200">
Expand Down
4 changes: 2 additions & 2 deletions src/components/forms/login.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -90,8 +90,8 @@ export const LoginForm = () => {

Cookies.set('ppdb_admin', res.data.token);
session.setToken(res.data.token);
session.loadUserInfo();
router.push('/me');
// session.loadUserInfo();
// router.push('/me');
}
}).catch(e => {
actions.setSubmitting(false);
Expand Down
14 changes: 11 additions & 3 deletions src/components/navbar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,25 @@ import React from 'react'
import { useSessionStore } from '@/contexts/sessionContext';
import Cookies from 'js-cookie'
import Link from 'next/link'
import { useRouter, usePathname } from 'next/navigation'

export const Navbar = () => {
const router = useRouter();
const path = usePathname();
const session = useSessionStore();
const tokenAdmin = Cookies.get('ppdb_admin');

React.useEffect(() => {
if (tokenAdmin) {
session.setToken(tokenAdmin);
session.loadUserInfo();
if (!session.token) session.setToken(tokenAdmin);
if (!session.username.length) session.loadUserInfo(() => {
session.reset();
Cookies.remove('ppdb_admin');
});
} else if (!tokenAdmin && path !== '/') {
router.push('/');
}
}, [tokenAdmin]);
}, [tokenAdmin, session, router, path]);
return (
<div className="navbar bg-base-100">
<div className="navbar-start">
Expand Down
27 changes: 22 additions & 5 deletions src/contexts/sessionContext.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,13 @@ export type UserSession = {
email: string;
status: UserStatus;
token?: string;
failed: boolean;
}

export type UserAction = {
updateState: (state: UserSession) => void;
setToken: (token: string) => void;
loadUserInfo: () => void;
loadUserInfo: (cb?: () => void) => void;
reset: () => void;
}

Expand All @@ -27,17 +28,32 @@ export const useSessionStore = create<UserSession & UserAction>((set, state) =>
id: 0,
status: UserStatus.NonActive,
username: '',
failed: false,
updateState: (state) => set(() => state),
setToken: (token) => set((st) => ({ ...st, token })),
loadUserInfo: () => {
loadUserInfo: (onFail) => {
const st = state();
fetch('/api/auth/profile', {
if (!st.failed) fetch('/api/auth/profile', {
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${st.token}`,
},
}).then(r => r.json()).then(res => {
set((st) => ({ ...st, ...res.data }));
}).then(r => {
if (r.status !== 200) {
if (onFail) onFail();

set((st) => ({ ...st, failed: true }));
return r.text();
}

return r.json();
}).then(res => {
if (typeof res === 'string') return;

set((st) => ({ ...st, ...res.data, failed: false, }));
}).catch(() => {
if (onFail) onFail();
set((st) => ({ ...st, failed: true }))
});
},
reset: () => set(() => ({
Expand All @@ -46,5 +62,6 @@ export const useSessionStore = create<UserSession & UserAction>((set, state) =>
status: UserStatus.NonActive,
username: '',
token: undefined,
failed: false,
})),
}));

0 comments on commit eda089f

Please sign in to comment.