Skip to content

Commit

Permalink
fix: 라우터 이슈 해결
Browse files Browse the repository at this point in the history
  • Loading branch information
ddarkr committed Feb 4, 2024
1 parent 1b7031b commit e6f2d5f
Show file tree
Hide file tree
Showing 15 changed files with 85 additions and 61 deletions.
2 changes: 1 addition & 1 deletion jest.setup.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { matchers } from '@emotion/jest';
import '@testing-library/jest-dom';
import '@testing-library/jest-dom/extend-expect';

jest.mock('next/router', () => require('next-router-mock'));
jest.mock('next/compat/router', () => require('next-router-mock'));

window.matchMedia = query => ({
matches: false,
Expand Down
2 changes: 1 addition & 1 deletion src/components/add/LinkInput.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ export default function LinkInput({ initialLink, openGraph, saveOpenGraph }: Lin

return (
<div css={LinkInputCss}>
{openGraph ? (
{openGraph && asPath ? (
<LinkThumbnail
edit={asPath.includes('add')}
openGraph={openGraph}
Expand Down
4 changes: 3 additions & 1 deletion src/components/common/NavigationBar/NavigationBar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,9 @@ export default function NavigationBar(props: NavigationBarProps) {
} else if (backLink) {
router.push(backLink, undefined, { scroll: backLinkScrollOption });
} else {
router.back();
if (router.back) {
router.back();
}
}
};

Expand Down
12 changes: 7 additions & 5 deletions src/components/common/ToastSection.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import React, { useEffect, useState } from 'react';
import Router from 'next/router';
import { useRouter } from 'next/compat/router';
import { css, Theme, useTheme } from '@emotion/react';
import { AnimatePresence, motion } from 'framer-motion';
import isNil from 'lodash/isNil';
Expand All @@ -12,6 +12,7 @@ import { CloseIcon } from './icons';
export default function ToastSection() {
const { currentToast } = useToast();
const theme = useTheme();
const router = useRouter();
const [isClipboardToastVisible, setClipboardToastVisible] = useState(true);

useEffect(() => {
Expand All @@ -20,10 +21,11 @@ export default function ToastSection() {

const onClickClipboardToast = () => {
setClipboardToastVisible(false);
Router.push({
pathname: currentToast?.clipboardConfig?.type === 'TEXT' ? '/add/text' : '/add/link',
query: { isClipboard: true },
});
router &&
router.push({
pathname: currentToast?.clipboardConfig?.type === 'TEXT' ? '/add/text' : '/add/link',
query: { isClipboard: true },
});
};

const onClickCloseButton = (e: React.MouseEvent<HTMLElement, MouseEvent>) => {
Expand Down
27 changes: 14 additions & 13 deletions src/components/home/Thumbnail.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import React from 'react';
import { useRouter } from 'next/router';
import { useRouter } from 'next/compat/router';
import { css, Theme } from '@emotion/react';
import { motion, Variants } from 'framer-motion';

Expand All @@ -17,22 +17,23 @@ export interface ContentThumbnailProps
}

function Thumbnail({ id, type, tags, content, openGraph }: ContentThumbnailProps) {
const { push } = useRouter();
const router = useRouter();

const moveToInspirationView = (id: number) => {
recordEvent({ action: '영감 상세 조회', value: type });
push(
{
query: {
modal: 'inspirationView',
id,
router &&
router.push(
{
query: {
modal: 'inspirationView',
id,
},
},
},
{ pathname: 'content', query: { id } },
{
scroll: false,
}
);
{ pathname: 'content', query: { id } },
{
scroll: false,
}
);
};

return (
Expand Down
14 changes: 8 additions & 6 deletions src/hooks/analytics/useRecordPageview.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { useEffect } from 'react';
import { useRouter } from 'next/router';
import { useRouter } from 'next/compat/router';

import { IS_PRODUCTION } from '~/constants/common';
import { gaPageview } from '~/libs/ga';
Expand All @@ -14,9 +14,11 @@ export function useRecordPageview() {
mixpanelTrack('Page view', { url, category: process.env.WEB_VERSION });
};

if (IS_PRODUCTION) router.events.on('routeChangeComplete', recordPageview);
return () => {
if (IS_PRODUCTION) router.events.off('routeChangeComplete', recordPageview);
};
}, [router.events]);
if (router) {
if (IS_PRODUCTION) router.events.on('routeChangeComplete', recordPageview);
return () => {
if (IS_PRODUCTION) router.events.off('routeChangeComplete', recordPageview);
};
}
}, [router]);
}
6 changes: 5 additions & 1 deletion src/hooks/common/useInternalRouter.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useRouter } from 'next/router';
import { useRouter } from 'next/compat/router';
import { UrlObject } from 'url';

export type RouterPathType =
Expand All @@ -25,6 +25,10 @@ export type RouterPathType =
export default function useInternalRouter() {
const router = useRouter();

if (!router) {
throw new Error('useInternalRouter must be used under Next.js Pages Router');
}

return {
...router,
push(path: RouterPathType, as?: UrlObject | string, options?: TransitionOptions) {
Expand Down
4 changes: 2 additions & 2 deletions src/hooks/common/useLoginRedirect.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useRouter } from 'next/router';
import { useRouter } from 'next/compat/router';

import { sessionStorageRedirectKey } from '~/constants/sessionStorage';

Expand All @@ -15,7 +15,7 @@ export function useLoginRedirect() {
const goRedirect = () => {
const redirect = getRedirect();
if (!redirect) return;
router.replace(redirect);
router && router.replace(redirect);
sessionStorage.removeItem(sessionStorageRedirectKey);
};

Expand Down
11 changes: 8 additions & 3 deletions src/hooks/common/useRouterQuery/useRouterQuery.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useRouter } from 'next/router';
import { useRouter } from 'next/compat/router';

function useQueryParam(key: string): string | string[] | undefined;

Expand All @@ -8,8 +8,13 @@ function useQueryParam<T>(
key: string,
parser?: (value: string | string[]) => T
): (string | string[] | T) | undefined {
const { query } = useRouter();
const result = query[key];
const router = useRouter();

if (!router) {
throw new Error('useQueryParam must be used under Next.js Pages Router');
}

const result = router.query[key];

if (result === undefined) return undefined;
if (parser) return parser(result);
Expand Down
4 changes: 2 additions & 2 deletions src/pages/add/tag.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { useCallback, useRef, useState } from 'react';
import { useRouter } from 'next/router';
import { useRouter } from 'next/compat/router';
import { motion } from 'framer-motion';

import { GhostButton } from '~/components/common/Button';
Expand Down Expand Up @@ -72,7 +72,7 @@ export default function TagPage() {
<GhostButton
size="large"
onClick={() => {
router.back();
router && router.back();
}}
>
완료
Expand Down
17 changes: 9 additions & 8 deletions src/pages/password/index.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { FormEvent, useState } from 'react';
import { useRouter } from 'next/router';
import { useRouter } from 'next/compat/router';
import { css, Theme } from '@emotion/react';

import { CTAButton } from '~/components/common/Button';
Expand All @@ -16,17 +16,18 @@ import { validator } from '~/utils/validator';
export default function PasswordReset() {
const { fireToast } = useToast();
const email = useInput({ useDebounce: true });
const { push } = useRouter();
const router = useRouter();
const [emailError, setEmailError] = useState('');
const { mutate: sendPasswordResetEmailMutation, isLoading: isSendPasswordResetEmailLoading } =
useSendPasswordResetEmailMutation({
onSuccess: () => {
push({
pathname: '/password/sent-email',
query: {
email: email.value,
},
});
router &&
router.push({
pathname: '/password/sent-email',
query: {
email: email.value,
},
});
},
onError: () => {
fireToast({
Expand Down
6 changes: 4 additions & 2 deletions src/pages/password/sent-email.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useRouter } from 'next/router';
import { useRouter } from 'next/compat/router';
import { css, Theme } from '@emotion/react';

import { CTAButton } from '~/components/common/Button';
Expand All @@ -8,7 +8,9 @@ import { FixedSpinner } from '~/components/common/Spinner';
import useInternalRouter from '~/hooks/common/useInternalRouter';

export default function SentPasswordResetEmail() {
const { query } = useRouter();
const router = useRouter();
if (!router) throw new Error('No router');
const { query } = router;
const { push } = useInternalRouter();

return (
Expand Down
6 changes: 3 additions & 3 deletions src/pages/signup/email-verified.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { FormEvent, useState } from 'react';
import Router from 'next/router';
import { useRouter } from 'next/compat/router';
import { css, Theme } from '@emotion/react';

import { CTABottomButton } from '~/components/common/Button';
Expand All @@ -19,6 +19,7 @@ import { validator } from '~/utils/validator';

export default function SignUpEmailVerified() {
const { fireToast } = useToast();
const router = useRouter();
const queryEmail = useRouterQuery('email', String);

const nickname = useInput({ useDebounce: true });
Expand Down Expand Up @@ -56,8 +57,7 @@ export default function SignUpEmailVerified() {
confirmPassword: passwordRepeat.value,
});

// NOTE: 이렇게 작성하지 않으면 router.push가 되지않는 이슈
Router.push({ pathname: '/signup/information', query: { email: queryEmail } });
router && router.push({ pathname: '/signup/information', query: { email: queryEmail } });
};

// NOTE: 닉네임 에러 메세지 설정 이펙트
Expand Down
24 changes: 13 additions & 11 deletions src/pages/signup/index.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { FormEvent, useEffect, useState } from 'react';
import { useRouter } from 'next/router';
import { useRouter } from 'next/compat/router';
import { css, Theme } from '@emotion/react';

import { CTAButton } from '~/components/common/Button';
Expand Down Expand Up @@ -111,12 +111,13 @@ function useSignupWithCheckingEmail(email: string) {
const { mutate: emailSendMutate } = useSignupSendEmailMutation({
onSuccess: () => {
recordEvent({ action: 'Signup', value: '이메일 인증 요청', label: '이메일 발송 화면' });
router.push({
pathname: '/signup/sent-email',
query: {
email: email,
},
});
router &&
router.push({
pathname: '/signup/sent-email',
query: {
email: email,
},
});
},
onError: data => {
if (data.message) fireToast({ content: data.message });
Expand Down Expand Up @@ -155,10 +156,11 @@ function useSignupWithCheckingEmail(email: string) {
label: '이메일 발송 화면',
});
fireToast({ content: '이미 인증된 메일입니다.' });
router.push({
pathname: '/signup/email-verified',
query: { email },
});
router &&
router.push({
pathname: '/signup/email-verified',
query: { email },
});
} else {
emailSendMutate({ email });
}
Expand Down
7 changes: 5 additions & 2 deletions src/pages/signup/sent-email.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { useEffect, useState } from 'react';
import { useRouter } from 'next/router';
import { useRouter } from 'next/compat/router';
import { css, Theme } from '@emotion/react';

import { CTAButton, FilledButton } from '~/components/common/Button';
Expand All @@ -15,7 +15,7 @@ import { recordEvent } from '~/utils/analytics';
import { validator } from '~/utils/validator';

export default function SignupSentEmail() {
const { query, push } = useRouter();
const router = useRouter();
const { fireToast } = useToast();
const [isModalOpen, setIsModalOpen] = useState(false);
const {
Expand All @@ -31,6 +31,9 @@ export default function SignupSentEmail() {
isLoading: emailSendingLoading,
} = useSignupSendEmailMutation({});

if (!router) throw new Error('router is not defined');
const { query, push } = router;

const handleEmailChecking = () => {
if (query.email !== undefined && validator({ type: 'email', value: query.email as string })) {
checkEmailStatusMutate({ email: query.email as string });
Expand Down

0 comments on commit e6f2d5f

Please sign in to comment.