Skip to content

Commit

Permalink
fix: call api 401 status (#50)
Browse files Browse the repository at this point in the history
* fix: call api 401 status

* fix: react hooks must be called in the exact same order in every component render
  • Loading branch information
JohnsonMao authored Jun 9, 2024
1 parent 6f0b4a9 commit e902061
Show file tree
Hide file tree
Showing 7 changed files with 65 additions and 78 deletions.
32 changes: 9 additions & 23 deletions components/Profile/MyGroup/GroupCard.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import MoreVertOutlinedIcon from '@mui/icons-material/MoreVertOutlined';
import Image from '@/shared/components/Image';
import emptyCoverImg from '@/public/assets/empty-cover.png';
import useMutation from '@/hooks/useMutation';
import { GROUP_API_URL } from '@/redux/actions/group';
import { timeDuration } from '@/utils/date';
import {
StyledAreas,
Expand Down Expand Up @@ -38,28 +37,15 @@ function GroupCard({
const router = useRouter();
const [anchorEl, setAnchorEl] = useState(null);

const apiUpdateGrouping = useMutation(
() =>
fetch(`${GROUP_API_URL}/${_id}`, {
method: 'PUT',
body: JSON.stringify({ isGrouping: !isGrouping }),
headers: {
'Content-Type': 'application/json',
},
}),
{ onSuccess: onUpdateGrouping },
);
const apiUpdateGrouping = useMutation(`/activity/${_id}`, {
method: 'PUT',
onSuccess: onUpdateGrouping,
});

const apiDeleteGroup = useMutation(
() =>
fetch(`${GROUP_API_URL}/${_id}`, {
method: 'DELETE',
headers: {
'Content-Type': 'application/json',
},
}),
{ onSuccess: onDeleteGroup },
);
const apiDeleteGroup = useMutation(`/activity/${_id}`, {
method: 'DELETE',
onSuccess: onDeleteGroup,
});

const handleMenu = (event) => {
event.preventDefault();
Expand All @@ -72,7 +58,7 @@ function GroupCard({

const handleGrouping = () => {
handleClose();
apiUpdateGrouping.mutate();
apiUpdateGrouping.mutate({ isGrouping: !isGrouping });
};

const handleDeleteGroup = () => {
Expand Down
13 changes: 6 additions & 7 deletions components/Profile/MyGroup/index.jsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
import { Fragment, useState } from 'react';
import styled from '@emotion/styled';
import { Box, Typography } from '@mui/material';
import { useSelector } from 'react-redux';
import { GROUP_API_URL } from '@/redux/actions/group';
import useFetch from '@/hooks/useFetch';
import GroupCard from './GroupCard';
import LoadingCard from './LoadingCard';
Expand All @@ -26,12 +24,9 @@ const StyledGroupsWrapper = styled.div`
`;

const MyGroup = ({ hasTitle = true, sx, userId }) => {
if (!userId) {
return <Typography py={7.5}>趕快發起屬於你的揪團吧~</Typography>;
}

const [response, setResponse] = useState(null);
const { isFetching } = useFetch(`${GROUP_API_URL}/user/${userId}`, {
const { isFetching } = useFetch(`/activity/user/${userId}`, {
enabled: !!userId,
onSuccess: setResponse,
});

Expand Down Expand Up @@ -75,6 +70,10 @@ const MyGroup = ({ hasTitle = true, sx, userId }) => {
});
};

if (!userId) {
return <Typography py={7.5}>趕快發起屬於你的揪團吧~</Typography>;
}

return (
<StyledGroupsWrapper sx={sx}>
{hasTitle && (
Expand Down
21 changes: 15 additions & 6 deletions hooks/useFetch.jsx
Original file line number Diff line number Diff line change
@@ -1,20 +1,29 @@
import { useEffect, useReducer, useState } from 'react';
import { useSelector } from 'react-redux';
import { BASE_URL } from '@/constants/common';

const useFetch = (url, { initialValue, onSuccess } = {}) => {
const useFetch = (url, { enabled = true, initialValue, onSuccess } = {}) => {
const { token } = useSelector((state) => state.user);
const [render, refetch] = useReducer((pre) => !pre, true);
const [data, setData] = useState(initialValue);
const [isFetching, setIsFetching] = useState(true);
const [isFetching, setIsFetching] = useState(enabled);
const [isError, setIsError] = useState(false);

useEffect(() => {
let pass = true;
if (!enabled) return;

if (url.includes('undefined')) return undefined;
const endpoint = url.startsWith('http') ? url : `${BASE_URL}${url}`;
const headers = {
'Content-Type': 'application/json',
Authorization: `Bearer ${token}`,
};
const requestData = { headers }
let pass = true;

setIsFetching(true);
setIsError(false);

fetch(url)
fetch(endpoint, requestData)
.then((res) => res.json())
.then((json) => pass && setData(json))
.catch(() => setIsError(true))
Expand All @@ -23,7 +32,7 @@ const useFetch = (url, { initialValue, onSuccess } = {}) => {
return () => {
pass = false;
};
}, [url, render]);
}, [enabled, token, url, render]);

useEffect(() => {
if (onSuccess) onSuccess(data);
Expand Down
19 changes: 17 additions & 2 deletions hooks/useMutation.jsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,28 @@
import { useState } from 'react';
import { useSelector } from 'react-redux';
import { BASE_URL } from '@/constants/common';

const useMutation = (mutateFn, { onSuccess, onError } = {}) => {
const useMutation = (url, { method, onSuccess, onError } = {}) => {
const { token } = useSelector((state) => state.user);
const [isLoading, setIsLoading] = useState(false);
const [isError, setIsError] = useState(false);

const mutate = (values) => {
const endpoint = url.startsWith('http') ? url : `${BASE_URL}${url}`;
const headers = {
'Content-Type': 'application/json',
Authorization: `Bearer ${token}`,
};
const requestData = {
method,
body: JSON.stringify(values),
headers,
}

setIsLoading(true);
setIsError(false);

mutateFn(values)
fetch(endpoint, requestData)
.then((res) => res.json())
.then(onSuccess)
.catch((e) => {
Expand Down
22 changes: 6 additions & 16 deletions pages/group/create/index.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import useMutation from '@/hooks/useMutation';
import SEOConfig from '@/shared/components/SEO';
import Navigation from '@/shared/components/Navigation_v2';
import Footer from '@/shared/components/Footer_v2';
import { GROUP_API_URL } from '@/redux/actions/group';

function CreateGroupPage() {
const { pushSnackbar } = useSnackbar();
Expand All @@ -25,22 +24,13 @@ function CreateGroupPage() {
[router?.asPath],
);

const { mutate, isLoading } = useMutation(
(values) =>
fetch(GROUP_API_URL, {
method: 'POST',
body: JSON.stringify(values),
headers: {
'Content-Type': 'application/json',
},
}),
{
onSuccess: () => {
pushSnackbar({ message: '已成功發布揪團' });
router.replace('/profile?id=my-group');
},
const { mutate, isLoading } = useMutation('/activity', {
method: 'POST',
onSuccess: () => {
pushSnackbar({ message: '已成功發布揪團' });
router.replace('/profile?id=my-group');
},
);
});

return (
<>
Expand Down
6 changes: 3 additions & 3 deletions pages/group/detail/index.jsx
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
import React, { useMemo } from 'react';
import { useRouter } from 'next/router';
import { useSelector } from 'react-redux';
import SEOConfig from '@/shared/components/SEO';
import GroupDetail from '@/components/Group/detail';
import GroupEmpty from '@/components/Group/detail/Empty';
import Navigation from '@/shared/components/Navigation_v2';
import Footer from '@/shared/components/Footer_v2';
import useFetch from '@/hooks/useFetch';
import { BASE_URL } from '@/constants/common';

function GroupPage() {
const router = useRouter();
const { id } = router.query;
const { data, isFetching, isError } = useFetch(`${BASE_URL}/activity/${id}`);
const { data, isFetching, isError } = useFetch(`/activity/${id}`, {
enabled: !!id,
});
const source = data?.data?.[0];

const SEOData = useMemo(
Expand Down
30 changes: 9 additions & 21 deletions pages/group/edit/index.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,15 @@ import useMutation from '@/hooks/useMutation';
import SEOConfig from '@/shared/components/SEO';
import Navigation from '@/shared/components/Navigation_v2';
import Footer from '@/shared/components/Footer_v2';
import { GROUP_API_URL } from '@/redux/actions/group';
import { BASE_URL } from '@/constants/common';

function EditGroupPage() {
const { pushSnackbar } = useSnackbar();
const router = useRouter();
const me = useSelector((state) => state.user);
const { id } = router.query;
const { data, isFetching } = useFetch(`${BASE_URL}/activity/${id}`);
const { data, isFetching } = useFetch(`/activity/${id}`, {
enabled: !!id,
});
const source = data?.data?.[0];

const SEOData = useMemo(
Expand All @@ -36,25 +36,13 @@ function EditGroupPage() {

const goToDetail = () => router.replace(`/group/detail?id=${id}`);

const { mutate, isLoading } = useMutation(
(values) => {
if (!id || id.includes('/')) return Promise.reject();

return fetch(`${GROUP_API_URL}/${id}`, {
method: 'PUT',
body: JSON.stringify(values),
headers: {
'Content-Type': 'application/json',
},
});
},
{
onSuccess: () => {
pushSnackbar({ message: '已發布修改' });
router.replace('/profile?id=my-group');
},
const { mutate, isLoading } = useMutation(`/activity${id}`, {
method: 'PUT',
onSuccess: () => {
pushSnackbar({ message: '已發布修改' });
router.replace('/profile?id=my-group');
},
);
});

useEffect(() => {
if (!me?._id) router.push('/login');
Expand Down

0 comments on commit e902061

Please sign in to comment.