Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/search page again #26

Merged
merged 5 commits into from
Jan 19, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 20 additions & 13 deletions src/components/SearchBar/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,22 +5,23 @@ import SearchIcon from '@mui/icons-material/Search';

import CategoryChips from '../CategoryChips';
import { Item } from '../../models/item';
import { getSearchAPICall } from '../../hooks/api/search/search';
import { Categories, Seasons } from '../../data/enumLists';
import { Categories, Seasons, Status } from '../../data/enumLists';

interface SearchBarProps {
searchKeyWord: string;
categorySelected: string[];
seasonSelected: string[];
filterSelected: string[];
handleSearch?: (a: string) => void;
}

export default function SearchBar(props: SearchBarProps) {
const navigate = useNavigate();
const emptyStrArray: string[] = [];
const [searchKeyWord, setSearchKeyWord] = useState('');
const [categorySelected, setCategorySelected] = useState(emptyStrArray);
const [seasonSelected, setSeasonSelected] = useState(emptyStrArray);
const [filterSelected, setFilterSelected] = useState(emptyStrArray);
// const emptyStrArray: string[] = [];
const [searchKeyWord, setSearchKeyWord] = useState(props.searchKeyWord);
const [categorySelected, setCategorySelected] = useState(props.categorySelected);
const [seasonSelected, setSeasonSelected] = useState(props.seasonSelected);
const [filterSelected, setFilterSelected] = useState(props.filterSelected);

const handleChange: React.ChangeEventHandler<HTMLInputElement> = (event) => {
setSearchKeyWord(event.target.value);
Expand All @@ -44,7 +45,7 @@ export default function SearchBar(props: SearchBarProps) {

const handleSubmit: React.FormEventHandler<HTMLFormElement> = (e) => {
e.preventDefault();
const keyWordQueryString = `keyword=${encodeURIComponent(searchKeyWord)}`;
const keyWordQueryString = `text=${encodeURIComponent(searchKeyWord)}`;
const categoryQueryString = categorySelected
.map((category) => `category=${encodeURIComponent(category)}`)
.join('&');
Expand All @@ -53,10 +54,9 @@ export default function SearchBar(props: SearchBarProps) {
const queryString = [keyWordQueryString, categoryQueryString, seasonQueryString, filterQueryString]
.filter((query) => !!query)
.join('&');
const url = `/search/?${queryString}`;
getSearchAPICall(url).then(() => {
navigate(url);
});
const url = `/search?${queryString}`;
navigate(url);
if (props.handleSearch) props.handleSearch(url);
};

const initCategories = Categories.map((value) => {
Expand All @@ -75,7 +75,14 @@ export default function SearchBar(props: SearchBarProps) {
const item: Item = { label: value, isSelected: false };
return item;
});
const initFilter: Item[] = [{ label: '대여 가능', isSelected: false }];
const initFilter = Status.map((value) => {
if (props.filterSelected.includes(value)) {
const item: Item = { label: value, isSelected: true };
return item;
}
const item: Item = { label: value, isSelected: false };
return item;
});

return (
<Box display={'flex'} flexDirection={'column'} alignItems={'center'}>
Expand Down
1 change: 1 addition & 0 deletions src/data/enumLists.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@ import { Season, Category } from '../models/enum';

export const Seasons = Object.values(Season);
export const Categories = Object.values(Category);
export const Status = ['대여가능', '대여중', '대여불가능'];
25 changes: 22 additions & 3 deletions src/hooks/api/search/search.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,30 @@ import axios, { AxiosError } from 'axios';

import { SEARCH_MESSAGE } from '../../../data/messages';

interface Owner {
id?: number;
nickname?: string;
location?: string;
}
interface SearchClothesRes {
id?: number;
closetId: number;
category?: string;
season?: string;
status: string;
isOpen: boolean;
name: string;
tag?: string;
image?: string;
owner: Owner;
isWished: boolean;
}

export async function getSearchAPICall(url: string) {
try {
const response = await axios.get(`${process.env.REACT_APP_API_URL}${url}`);
const response = await axios.get<SearchClothesRes[]>(`${process.env.REACT_APP_API_URL}${url}`);
if (response.status === 200) {
const { searchResult } = response.data;
sessionStorage.setItem('searchResult', searchResult);
return response.data;
}
} catch (err) {
if (err instanceof AxiosError) {
Expand All @@ -17,4 +35,5 @@ export async function getSearchAPICall(url: string) {
enqueueSnackbar(SEARCH_MESSAGE.SEARCH_FAIL, { variant: 'error' });
}
}
return null;
}
2 changes: 1 addition & 1 deletion src/pages/Main/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ export function MainPage() {
스타일을 공유하고 다른 사람의 스타일을 빌려보세요
</Typography>
</Box>
<SearchBar searchKeyWord={''} categorySelected={[]} seasonSelected={[]} />
<SearchBar searchKeyWord={''} categorySelected={[]} seasonSelected={[]} filterSelected={[]} />
</Box>
{!!applies && applies.length > 0 && (
<Box sx={{ mt: 5, mb: 10 }} display={'flex'} flexDirection={'column'} alignItems={'center'}>
Expand Down
93 changes: 93 additions & 0 deletions src/pages/Search/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
import { useSearchParams } from 'react-router-dom';
import { useState } from 'react';
import { Box, Typography } from '@mui/material';

import { getSearchAPICall } from '../../hooks/api/search/search';
import SearchBar from '../../components/SearchBar';
import ClothesPreviewCard from '../../components/ClothesPreviewCard';

interface Owner {
id?: number;
nickname?: string;
location?: string;
}
interface SearchClothesRes {
id?: number;
closetId: number;
category?: string;
season?: string;
status: string;
isOpen: boolean;
name: string;
tag?: string;
image?: string;
owner: Owner;
isWished: boolean;
}

export function SearchPage() {
const [searchParams] = useSearchParams();
// const location = useLocation();
// const queryString = location.search;
// const url = `/search${queryString}`;

const searchKeyWord = searchParams.get('text') || '';
const categorySelected = searchParams.getAll('category');
const seasonSelected = searchParams.getAll('season');
const filterSelected = searchParams.getAll('status');

const defaultResult: JSX.Element = (
<Typography width="100%" textAlign="center" sx={{ mt: '50px', color: 'gray', fontSize: 20 }}>
검색 결과가 없어요
</Typography>
);

const emptySearchArray: SearchClothesRes[] = [];
const [searchedClothes, setSearchedClothes] = useState(emptySearchArray);
const handleSearch = async (query: string) => {
try {
const result = await getSearchAPICall(query);
if (result) {
setSearchedClothes(result);
} else setSearchedClothes(emptySearchArray);
} catch (error) {
//
}
};
// handleSearch(url);

const clothesCards = searchedClothes
? searchedClothes.map((clothes: SearchClothesRes) => {
const { id, name, status, owner, isWished } = clothes;
return (
<Box sx={{ margin: 3, display: 'inline-block' }}>
<ClothesPreviewCard
key={id}
clothesId={id || 0}
clothesname={name}
imgsrc={''}
status={status}
userid={owner.id || 0}
username={'닉네임'}
isWished={isWished}
/>
</Box>
);
})
: [];

return (
<>
<Box sx={{ paddingTop: '24px', backgroundColor: '#E9E9E9' }}>
<SearchBar
searchKeyWord={searchKeyWord}
categorySelected={categorySelected}
seasonSelected={seasonSelected}
filterSelected={filterSelected}
handleSearch={handleSearch}
/>
</Box>
{clothesCards && clothesCards.length > 0 ? clothesCards : defaultResult}
</>
);
}
2 changes: 2 additions & 0 deletions src/route/index.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { Route, Routes } from 'react-router-dom';

import { SearchPage } from '../pages/Search';
import { RegisterPage } from '../pages/Register';
import { ProfilePage } from '../pages/Profile';
import MyPage from '../pages/Mypage';
Expand All @@ -20,6 +21,7 @@ export function RouteComponent() {
<Route path="/clothes/:id" element={<ClothesPage />} />
<Route path="/profile" element={<ProfilePage />} />
<Route path="/mypage" element={<MyPage />} />
<Route path="/search" element={<SearchPage />} />
</Routes>
);
}