Skip to content

Commit 9a130c4

Browse files
committed
fix: some bugs
1 parent 96c0bfc commit 9a130c4

18 files changed

Lines changed: 216 additions & 156 deletions

File tree

src/App.tsx

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
import { useState } from "react";
21
import "./App.css";
32
import getCotails from "./services/cotails-api";
43

src/components/FilterResult/CustomSelect/CustomSelect.tsx

Lines changed: 31 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ import {
77
SelectTrigger,
88
SelectValue,
99
} from "@/components/ui/select";
10-
import getCotails from "@/services/cotails-api";
10+
import getData from "@/services/cotails-api";
1111
import { useQuery } from "@tanstack/react-query";
1212

1313
interface CustomSelectProps {
@@ -16,6 +16,7 @@ interface CustomSelectProps {
1616
placeholder: string;
1717
path?: string;
1818
options?: (string | boolean)[];
19+
parseKey?: string;
1920
}
2021

2122
async function getDataForFilter({
@@ -25,7 +26,7 @@ async function getDataForFilter({
2526
}) {
2627
const [path] = queryKey;
2728

28-
const response = getCotails(`${path}`);
29+
const response = getData(`${path}`);
2930

3031
return response;
3132
}
@@ -36,20 +37,37 @@ function CustomSelect({
3637
path,
3738
placeholder,
3839
options = [],
40+
parseKey,
3941
}: CustomSelectProps) {
40-
const { data, error } = useQuery([path], getDataForFilter);
42+
const { data, error, loading } = useQuery([path], getDataForFilter, {
43+
enabled: !!path,
44+
staleTime: Infinity,
45+
cacheTime: Infinity,
46+
refetchOnWindowFocus: false,
47+
});
4148

42-
const dataParse: undefined | string[] = data?.data;
49+
let dataParse: undefined | [string, string][];
50+
51+
if (parseKey && !loading) {
52+
dataParse = data?.data.map((dataObj: { [key: string]: string }) => [
53+
dataObj.id,
54+
dataObj[parseKey],
55+
]);
56+
} else {
57+
dataParse = data?.data.map((value: string) => [value, value]);
58+
}
4359

4460
const RenderSelectItems = () => {
45-
const optionArr = path ? dataParse : options;
61+
const refactorOptions = options?.map((value) => [value, value]);
62+
63+
const optionArr = path ? dataParse : refactorOptions;
4664

4765
if (optionArr === undefined) return "Loading data";
4866

49-
return optionArr.map((option: string | boolean) => {
67+
return optionArr.map(([key, value]) => {
5068
return (
51-
<SelectItem value={String(option)}>
52-
<span>{String(option)}</span>
69+
<SelectItem value={String(key)} key={String(key)}>
70+
<span>{String(value)}</span>
5371
</SelectItem>
5472
);
5573
});
@@ -64,6 +82,11 @@ function CustomSelect({
6482
<SelectValue placeholder={placeholder} />
6583
</SelectTrigger>
6684
<SelectContent>
85+
{loading && path !== undefined && (
86+
<SelectLabel>
87+
loading...
88+
</SelectLabel>
89+
)}
6790
<SelectGroup>
6891
<SelectLabel>
6992
{error && path !== undefined ? "Faild to load data" : placeholder}

src/components/FilterResult/FilterResult.css

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,11 @@
1111

1212
.filter-result > .apply-filters {
1313
background-color: #1d4ed8;
14+
transition: 0.4s background-color;
15+
16+
&:hover {
17+
background-color: #2563eb;
18+
}
1419
}
1520

1621
@media (max-width: 1440px) {

src/components/FilterResult/FilterResult.tsx

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -70,9 +70,7 @@ function FilterResult({ fields, searchPlaceholder }: FilterResultProps) {
7070
{Object.entries(fields).map(([key, config]) => {
7171
return (
7272
<CustomSelect
73-
placeholder={config.placeholder}
74-
path={config.path}
75-
options={config.options}
73+
{...config}
7674
value={filterData[key] || ""}
7775
setValue={(value: string) => handleFilterDataChange(key, value)}
7876
/>

src/components/Loader/Loader.tsx

Lines changed: 0 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,6 @@
11
import './Loader.css';
22

3-
// import { Status } from '../../enums';
4-
5-
// interface LoaderProps {
6-
// status: Status;
7-
// }
8-
93
function Loader() {
10-
console.log('Call lodaer');
11-
// alert('Call loader');
124
return <span className="loader"></span>;
135
}
146

src/components/PageSwitcher/PageSwitcher.tsx

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,6 @@ import {
2121
import "./PageSwitcher.css";
2222
import { PageData } from "../../pages/CocktailsPages/interfaces";
2323
import useCustomSearchParams from "@/hooks/useCustomSearchParams";
24-
import { Fragment } from "react/jsx-runtime";
2524

2625
interface PageSwitcherProps {
2726
metaData: PageData | null;
@@ -40,14 +39,12 @@ function PageSwitcher({ metaData }: PageSwitcherProps) {
4039

4140
const handlePageClick = (page: number) => {
4241
setSearchParams({
43-
// ...Object.fromEntries(searchParams.entries()),
4442
page: page.toString(),
4543
});
4644
};
4745

4846
const handlePerPageChange = (value: string) => {
4947
setSearchParams({
50-
// ...Object.fromEntries(searchParams.entries()),
5148
perPage: value,
5249
});
5350
};

src/components/interfaces.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ interface FilterFields {
33
placeholder: string;
44
path?: string;
55
options?: string[],
6+
parseKey?: string,
67
}
78
}
89

src/hooks/useCustomSearchParams.ts

Lines changed: 18 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { useLocation, useSearchParams } from "react-router-dom";
22
import useFavoritesId from "./useFavoritesId";
3-
import { useEffect, } from "react";
3+
import { useEffect, useRef, } from "react";
44

55
interface NewSearchParams {
66
[key: string]: string;
@@ -10,36 +10,42 @@ interface NewSearchParams {
1010
function useCustomSearchParams(): [URLSearchParams, (newSearchParams: NewSearchParams) => void] {
1111
const [searchParams, setSearchParams] = useSearchParams();
1212
const { pathname, search } = useLocation();
13+
const previousPathPart = useRef<string | null>(null);
1314
const favoritesId = useFavoritesId();
1415

1516
const page = searchParams.get('page') || '1';
1617
const perPage = searchParams.get('perPage') || '15';
1718
const pathPart: string = pathname.split("/")[1];
1819

19-
console.log('useCustomSearchParams: ', location);
20-
21-
// useEffect(() => {
22-
// window.scrollTo({
23-
// top: 0,
24-
// behavior: "smooth",
25-
// });
26-
// }, [pathname])
20+
useEffect(() => {
21+
window.scrollTo({
22+
top: 0,
23+
behavior: "smooth",
24+
});
25+
}, [pathPart, search])
2726

2827
useEffect(() => {
2928
const saveParams = localStorage.getItem(pathPart);
3029
const parsedParams = saveParams ? JSON.parse(saveParams) : {};
31-
if (pathPart === 'favourites') {
30+
31+
if (search && pathPart !== previousPathPart.current) {
32+
const searchParamsObject = Object.fromEntries(new URLSearchParams(search).entries());
33+
34+
setCustomSearchParams(searchParamsObject);
35+
} else if (pathPart === 'favourites') {
3236
setCustomSearchParams(parsedParams);
3337
} else {
3438
setCustomSearchParams(parsedParams);
3539
}
3640

41+
previousPathPart.current = pathPart;
42+
3743
}, [favoritesId, pathPart]);
3844

39-
const setCustomSearchParams = (newSearchParams: NewSearchParams) => {
45+
const setCustomSearchParams = (newSearchParams: NewSearchParams | URLSearchParams) => {
4046
const newSearchParamsConfig = { page, perPage, ...newSearchParams }
4147
if (pathPart === 'favourites') {
42-
setSearchParams({ id: favoritesId, ...newSearchParamsConfig });
48+
setSearchParams({...newSearchParamsConfig, id: favoritesId });
4349
localStorage.setItem(pathPart, JSON.stringify(newSearchParamsConfig));
4450
} else {
4551
setSearchParams(newSearchParamsConfig);

src/layouts/CocktailsLayout/filterFields.ts

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,11 @@
11
import { FilterFields } from "@/components/interfaces";
22

33
const filterFields: FilterFields = {
4+
'ingredientId': {
5+
placeholder: "Main ingredient",
6+
path: "/ingredients?perPage=1000",
7+
parseKey: 'name',
8+
},
49
'glass': {
510
placeholder: "Select a glass",
611
path: "/cocktails/glasses",

src/pages/CocktailsPages/CocktailList/CocktailList.tsx

Lines changed: 21 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,33 +1,46 @@
11
import "../../style/CardList.css";
22
import "./CocktailList.css";
33
import { ResponseData } from "../interfaces";
4-
import getCotails from "../../../services/cotails-api";
4+
import getData from "../../../services/cotails-api";
55
import { useQuery } from "@tanstack/react-query";
66
import CocktailCard from "../CocktailCard/CocktailCard";
77
import PageSwitcher from "../../../components/PageSwitcher/PageSwitcher";
88
import Loader from "../../../components/Loader/Loader";
99
import { Outlet, useLocation } from "react-router-dom";
10+
import { Button } from "@/components/ui/button";
11+
import useCustomSearchParams from "@/hooks/useCustomSearchParams";
1012

1113
async function getCards({ queryKey }: { queryKey: [string, string] }) {
12-
const [_key, search] = queryKey;
13-
const response = await getCotails(`/cocktails${search}`);
14+
const [, search] = queryKey;
15+
const response = await getData(`/cocktails${search}`);
1416

1517
return response;
1618
}
1719

1820
function CocktailList() {
21+
const [, setSearchParams] = useCustomSearchParams();
1922
const location = useLocation();
2023

2124
const { search } = location;
2225

23-
const { data, isLoading, error } = useQuery(["cocktails", search], getCards);
26+
const { data, isLoading, error } = useQuery(["cocktails", search], getCards, {
27+
staleTime: 5 * 60 * 1000,
28+
cacheTime: 15 * 60 * 1000,
29+
enabled: !!search,
30+
retry: 2,
31+
refetchOnWindowFocus: false,
32+
});
2433

2534
if (error) return <p>Error loading data.</p>;
2635

2736
const cards = data as ResponseData;
2837

2938
const isNoData = cards?.data?.length === 0;
3039

40+
const handleResetFilter = () => {
41+
setSearchParams({});
42+
};
43+
3144
return (
3245
<>
3346
{isLoading ? (
@@ -41,8 +54,11 @@ function CocktailList() {
4154
)}
4255

4356
{isNoData && !isLoading && (
44-
<div className="rest-filter">
57+
<div className="reset-filter">
4558
<h3 className="emty-data">No data available for this request</h3>
59+
<Button className="reset-filters-btn" onClick={handleResetFilter}>
60+
Reset Filter
61+
</Button>
4662
</div>
4763
)}
4864
<PageSwitcher metaData={cards?.meta || null} />

0 commit comments

Comments
 (0)