Skip to content

Commit

Permalink
Merge pull request #285 from Strong-Potato/270-fix-fix-react-query
Browse files Browse the repository at this point in the history
�Fix: fix react query
  • Loading branch information
JSH99 authored Jan 28, 2024
2 parents 15c829c + 219387a commit 670359c
Show file tree
Hide file tree
Showing 13 changed files with 115 additions and 60 deletions.
21 changes: 20 additions & 1 deletion src/api/spaces.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
journeyParams,
journeyPutParams,
PlaceParams,
SearchPlaceParams,
SpaceDateParams,
SpaceRegionParams,
} from '@/types/route';
Expand Down Expand Up @@ -56,7 +57,10 @@ export const getSpace = async (spaceId: number) => {
const response = await axios.get(`/api/spaces/${spaceId}`, {withCredentials: true});
return response.data;
} catch (error) {
console.log(error);
if (axios.isAxiosError(error)) {
console.log(error);
return error.response;
}
}
};

Expand Down Expand Up @@ -98,6 +102,21 @@ export const postPlaces = async ({spaceId, journeyId, placeIds}: PlaceParams) =>
}
};

// [POST] 장소 검색 일정 추가
export const postSearchPlaces = async ({spaceId, journeyId, places}: SearchPlaceParams) => {
try {
const response = await axios.post(
`/api/spaces/${spaceId}/places/search`,
{journeyId: journeyId, places: places},
{withCredentials: true},
);
console.log('[SUCCESS]', response);
return response;
} catch (error) {
console.error(error);
}
};

// [PUT] 일정 수정
export const putPlaces = async ({spaceId, places}: journeyPutParams) => {
try {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,5 +49,6 @@

.swiperSlideItem {
padding: 1rem 0;
min-width: 37.5rem;
}
}
14 changes: 4 additions & 10 deletions src/components/Route/DayMove/DayMove.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,13 +22,7 @@ function DayMove({journeysData, selectedPlaces, onClose, setIsEditMode}: DayMove
updatedSelectedDays[index] = !updatedSelectedDays[index];
setSelectedDays(updatedSelectedDays);

// TODO: 선택된 장소 카드 선택한 날짜 동선으로 이동
const journeysId = journeysData?.journeys?.[index]?.journeyId;
console.log('지우겠다', transformSelectedPlaces(selectedPlaces));
console.log('추가하겠다.', {
journeyId: journeysId,
placeIds: selectedPlaces.flatMap((place) => place.placeId),
});

await deletePlaces.mutateAsync({spaceId: Number(id), places: transformSelectedPlaces(selectedPlaces)});
await postPlaces.mutateAsync({
Expand All @@ -37,10 +31,10 @@ function DayMove({journeysData, selectedPlaces, onClose, setIsEditMode}: DayMove
placeIds: selectedPlaces.flatMap((place) => place.placeId),
});

setTimeout(() => {
onClose();
setIsEditMode(false);
}, 300);
// FIXME: 페이지에 잔류하면서 보여지는 데이터 갱신
window.location.reload();
onClose();
setIsEditMode(false);
};

return (
Expand Down
4 changes: 3 additions & 1 deletion src/components/Route/DeletePlacesModal/DeletePlacesModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,11 @@ function DeletePlacesModal({isOpen, onClose, setIsEditMode, placeList}: DeletePl

const deleteJourneys = async () => {
await deletePlaces.mutateAsync({spaceId: Number(id), places: placeList});

// FIXME: 페이지에 잔류하면서 보여지는 데이터 갱신
window.location.reload();
onClose();
setIsEditMode(false);
// FIXME: 삭제 후 리스트 자동 갱신 안 됨
};

return (
Expand Down
4 changes: 2 additions & 2 deletions src/components/Route/RouteTabPanel/RouteTabPanel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ import MapInTrip from '../MapInTrip/MapInTrip';

import {DateItem, Journey, MapInTripProps, PlaceList, SelectedPlace} from '@/types/route';

function RouteTabPanel({mapRef, center, journeysData}: MapInTripProps) {
function RouteTabPanel({mapRef, center, level, journeysData}: MapInTripProps) {
const navigate = useNavigate();
const {id} = useParams();
const [isEditMode, setIsEditMode] = useState(false);
Expand Down Expand Up @@ -63,7 +63,7 @@ function RouteTabPanel({mapRef, center, journeysData}: MapInTripProps) {
return (
<div className={styles.panelContainer}>
<div className={styles.mapContainer}>
<MapInTrip mapRef={mapRef} center={center} journeysData={journeysData} />
<MapInTrip mapRef={mapRef} center={center} level={level} journeysData={journeysData} />
<button className={styles.zoomInButton} onClick={() => navigate(`/trip/${id}/map`, {state: {id: id}})}>
<ZoomInIcon />
</button>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {usePostPlaces} from '@/hooks/Spaces/space';

import CustomToast from '@/components/CustomToast/CustomToast';

import {activeTabIndexState} from '@/recoil/spaces/trip';
import {journeyState} from '@/recoil/vote/addToJourney';
import {isBottomSlideOpenState} from '@/recoil/vote/bottomSlide';
const AddToJourney = ({placeId}: {placeId: number}) => {
Expand All @@ -23,6 +24,7 @@ const AddToJourney = ({placeId}: {placeId: number}) => {
const {mutateAsync: addToJourneyMutateAsync} = usePostPlaces();
const [journeyId, SetJourneyId] = useState(journeyAtom.journeys?.[1]?.journeyId);
const showToast = CustomToast();
const setSelectedTabIndex = useSetRecoilState(activeTabIndexState);

const handleSelect = (index: number) => {
const updatedSelectedDays = [...selectedDays];
Expand All @@ -34,12 +36,17 @@ const AddToJourney = ({placeId}: {placeId: number}) => {
SetJourneyId(newJourneyId);
};

const handleGoBackToJourney = () => {
navigate(`/trip/${spaceId}`);
setSelectedTabIndex(1);
};

//중복 선택 불가 추가
const handleAddToJourney = async () => {
const res = await addToJourneyMutateAsync({spaceId, journeyId, placeIds: [placeId]});
setIsBTOpen(false);
console.log('일정추가 res', res);
showToast('일정에 추가가 완료되었습니다.', true, '바로가기', () => navigate(`/trip/${spaceId}`));
showToast('일정에 추가가 완료되었습니다.', true, '바로가기', handleGoBackToJourney);
};

return (
Expand Down
19 changes: 17 additions & 2 deletions src/hooks/Spaces/space.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import {useMutation, useQuery, useQueryClient} from '@tanstack/react-query';
import {useMutation, useQuery, useQueryClient, useSuspenseQuery} from '@tanstack/react-query';

import {
deletePlaces,
Expand All @@ -7,6 +7,7 @@ import {
getRegions,
getSpace,
postPlaces,
postSearchPlaces,
putDates,
putExitSpace,
putPlaces,
Expand All @@ -15,7 +16,7 @@ import {

// [GET] 지역 리스트 조회
export const useGetRegions = () => {
return useQuery({
return useSuspenseQuery({
queryKey: ['spaces', 'city'],
queryFn: () => getRegions(),
});
Expand Down Expand Up @@ -58,6 +59,20 @@ export const usePostPlaces = () => {
});
};

// [POST] 일정 추가
export const usePostSearchPlaces = () => {
const queryClient = useQueryClient();
return useMutation({
mutationFn: postSearchPlaces,
onSuccess: () => {
queryClient.invalidateQueries({queryKey: ['spaces']});
queryClient.invalidateQueries({queryKey: ['journey']});
queryClient.invalidateQueries({queryKey: ['places']});
queryClient.invalidateQueries({queryKey: ['search']});
},
});
};

// [PUT] 일정 수정
export const usePutPlaces = () => {
const queryClient = useQueryClient();
Expand Down
12 changes: 5 additions & 7 deletions src/pages/AddPlaceFromVote/AddPlaceFromVote.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
import {Button} from '@chakra-ui/react';
import {useEffect} from 'react';
import {MdOutlineReplay as ResetIcon} from 'react-icons/md';
import {useLocation, useNavigate} from 'react-router-dom';
import {useRecoilState} from 'recoil';
import {useRecoilState, useSetRecoilState} from 'recoil';

import styles from './AddPlaceFromVote.module.scss';

Expand All @@ -16,23 +15,21 @@ import {SelectedPlaces} from '@/components/Route/AddPlace/FromVote/VoteCard/Vote

import BackIcon from '@/assets/back.svg?react';
import {selectedPlaceFromVoteState} from '@/recoil/spaces/selectPlace';
import {activeTabIndexState} from '@/recoil/spaces/trip';

import {Vote} from '@/types/route';

function AddPlaceFromVote() {
const goBack = useGoBack();
const {state} = useLocation();
const {id, journeyId, day} = state;
const {data: voteData, refetch} = useGetVoteListInfo(Number(id));
const {data: voteData} = useGetVoteListInfo(Number(id));
const [selectedPlaces, setSelectedPlaces] = useRecoilState<SelectedPlaces[]>(selectedPlaceFromVoteState);
const inProgressVotes = voteData?.data?.voteResponse?.filter((vote: Vote) => vote.voteStatus === '진행 중');
const completedVotes = voteData?.data?.voteResponse?.filter((vote: Vote) => vote.voteStatus === '결정 완료');
const postPlaces = usePostPlaces();
const navigate = useNavigate();

useEffect(() => {
refetch();
}, []);
const setSelectedTabIndex = useSetRecoilState(activeTabIndexState);

const addPlaces = async () => {
await postPlaces.mutateAsync({
Expand All @@ -41,6 +38,7 @@ function AddPlaceFromVote() {
placeIds: selectedPlaces.flatMap((place) => place.id),
});
navigate(`/trip/${id}`, {state: {id: id}});
setSelectedTabIndex(1);
};

const resetSelected = () => {
Expand Down
20 changes: 10 additions & 10 deletions src/pages/RegionSearch/RegionSearch.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ function RegionSearch() {
const [selectedRegions, setSelectedRegions] = useState<string[]>(prevRegion ? prevRegion : []);
const [filteredRegions, setFilteredRegions] = useState<Region[]>(regions);

if (spaceData.responseCode === 404) {
if (spaceData?.responseCode === 404) {
setSelectedRegions([]);
}

Expand All @@ -45,10 +45,10 @@ function RegionSearch() {
};

const handleRegionSelect = (regionName: string) => {
if (selectedRegions.includes(regionName)) {
setSelectedRegions((prevSelectedRegions) => prevSelectedRegions.filter((name) => name !== regionName));
if (selectedRegions?.includes(regionName)) {
setSelectedRegions((prevSelectedRegions) => prevSelectedRegions?.filter((name) => name !== regionName));
} else {
if (selectedRegions.length < 4) {
if (selectedRegions?.length < 4) {
setSelectedRegions((prevSelectedRegions) => [...prevSelectedRegions, regionName]);
} else {
showToast('최대 4개 도시까지 선택 가능합니다.', false, '');
Expand All @@ -73,9 +73,9 @@ function RegionSearch() {
/>
</header>
<div className={isInputFocused || regionValue ? styles.regionListsContainer__focus : styles.regionListsContainer}>
{filteredRegions.length ? (
{filteredRegions?.length ? (
<>
{filteredRegions.map((region) => (
{filteredRegions?.map((region) => (
<RegionList
key={region.cityName}
name={region.cityName}
Expand All @@ -89,9 +89,9 @@ function RegionSearch() {
<NoSearchResult />
)}
</div>
<div className={selectedRegions.length ? styles.regionChoiceContainer : ''}>
<div className={selectedRegions?.length ? styles.regionChoiceContainer : ''}>
<div className={styles.tagContainer}>
{selectedRegions.map((region) => (
{selectedRegions?.map((region) => (
<RegionTagItem
key={region}
label={region}
Expand All @@ -101,8 +101,8 @@ function RegionSearch() {
/>
))}
</div>
<Button isDisabled={!selectedRegions.length} zIndex='3' variant='CTAButton' onClick={editRegions}>
{selectedRegions.length ? `${selectedRegions.length}개 선택 완료` : '도시를 선택해주세요'}
<Button isDisabled={!selectedRegions?.length} zIndex='3' variant='CTAButton' onClick={editRegions}>
{selectedRegions?.length ? `${selectedRegions.length}개 선택 완료` : '도시를 선택해주세요'}
</Button>
</div>
</div>
Expand Down
26 changes: 16 additions & 10 deletions src/pages/Trip/CheckTrip.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import {Tab, TabIndicator, TabList, TabPanel, TabPanels, Tabs} from '@chakra-ui/react';
import {useEffect} from 'react';
import {AiOutlineBell as AlarmIcon} from 'react-icons/ai';
import {AiOutlineMenu as MenuIcon} from 'react-icons/ai';
import {FiPlus as PlusIcon} from 'react-icons/fi';
Expand All @@ -13,6 +14,7 @@ import useGoLogin from '@/hooks/useGoLogin';

import AlertModal from '@/components/AlertModal/AlertModal';

import {activeTabIndexState} from '@/recoil/spaces/trip';
import {isModalOpenState} from '@/recoil/vote/alertModal';

function CheckTrip() {
Expand All @@ -21,17 +23,21 @@ function CheckTrip() {
const setIsModal = useSetRecoilState(isModalOpenState);
const {mutate} = usePostSpace();
const navigate = useNavigate();
const setSelectedTabIndex = useSetRecoilState(activeTabIndexState);

if (recentSpaceData?.status === 403 || recentSpaceData?.status === 401) {
// 비로그인 유저
goLogin();
} else if (recentSpaceData?.responseCode === 404) {
// 유효한 여행 스페이스 없는 유저
setIsModal(true);
} else if (recentSpaceData?.data?.id) {
// 최근 방문 스페이스 있는 유저
navigate(`/trip/${recentSpaceData.data.id}`, {state: {id: recentSpaceData.data.id}});
}
useEffect(() => {
if (recentSpaceData?.status === 403 || recentSpaceData?.status === 401) {
// 비로그인 유저
goLogin();
} else if (recentSpaceData?.responseCode === 404) {
// 유효한 여행 스페이스 없는 유저
setIsModal(true);
} else if (recentSpaceData?.data?.id) {
// 최근 방문 스페이스 있는 유저
navigate(`/trip/${recentSpaceData?.data?.id}`, {state: {id: recentSpaceData?.data?.id}});
setSelectedTabIndex(0);
}
}, [recentSpaceData]);

const makeNewSpace = () => {
setIsModal(false);
Expand Down
Loading

0 comments on commit 670359c

Please sign in to comment.