Skip to content

Commit

Permalink
Merge pull request #34 from hdcola/tamara
Browse files Browse the repository at this point in the history
Add search + small fixes
  • Loading branch information
iasssy authored Nov 4, 2024
2 parents 1d16c9f + 16ffdfa commit 03869d8
Show file tree
Hide file tree
Showing 8 changed files with 81 additions and 56 deletions.
38 changes: 26 additions & 12 deletions src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,13 @@ function App() {
const loader = 'auto';

const [isInit, setIsInit] = useState<boolean>(false);
const [server, setServer] = useState<IServer>({});
const [server, setServer] = useState<IServer>({
isLoggedIn: false,
apiUrl: '',
authToken: '',
} as IServer);
const [cartCount, setCartCount] = useState<number>(0);
const [searchQuery, setSearchQuery] = useState<string>('');

const { authToken, logout, isLoggedIn } = useLoginStore();

Expand All @@ -58,7 +63,9 @@ function App() {
if (typeof error === 'object' && error && 'status' in error) {
if (error.status === 403) {
console.log('<< Unauthorized >>');
logout();
if (isLoggedIn) {
logout();
}
}
}
},
Expand All @@ -67,14 +74,13 @@ function App() {

// Setup server
useLayoutEffect(() => {
if (isLoggedIn) {
setServer({
apiUrl: import.meta.env.VITE_API_URL,
authToken: authToken,
});
} else {
setServer({
apiUrl: import.meta.env.VITE_API_URL,
authToken: authToken,
isLoggedIn: isLoggedIn || false,
});
if (!isLoggedIn) {
setCartCount(0);
setServer({ apiUrl: server.apiUrl });
}
setIsInit(true);
}, [isLoggedIn]);
Expand All @@ -84,7 +90,14 @@ function App() {
<CssBaseline />
<Container sx={{ height: '100%' }} disableGutters={lessThanXL}>
<AppContext.Provider
value={{ isInit, server, cartCount, setCartCount }}
value={{
isInit,
server,
cartCount,
setCartCount,
searchQuery,
setSearchQuery,
}}
>
<QueryClientProvider client={queryClient}>
<Router>
Expand Down Expand Up @@ -143,8 +156,9 @@ function App() {
}

interface IServer {
apiUrl?: string;
authToken?: string;
apiUrl: string;
authToken: string;
isLoggedIn: boolean;
}

export default App;
20 changes: 8 additions & 12 deletions src/api/useGetItems.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,20 +19,16 @@ interface IStore {
logo_url: string;
}

const fetchItems = async () => {
const fetchItems = async (searchQuery: string) => {
const apiUrl = import.meta.env.VITE_API_URL;
const { authToken } = useLoginStore.getState();

/* return axios.get(`${server.apiUrl}/api/items`, {
headers: { Authorization: `Bearer ${server.authToken}` },
}).then((res) => {
return { items: res.data as IItem[] };
}).catch((err) => {
throw new Error('Failed to fetch items');
}); */

let url = `${apiUrl}/api/items`;
if (searchQuery !== '') {
url += `?query=${searchQuery}`
}

const res = await axios.get(`${apiUrl}/api/items`, {
const res = await axios.get(url, {
headers: { Authorization: `Bearer ${authToken}` },
});
if (res.status === 200) {
Expand All @@ -41,10 +37,10 @@ const fetchItems = async () => {
throw new Error('Failed to fetch cart items');
}

const useGetItems = (enabled: boolean) => {
const useGetItems = (enabled: boolean, searchQuery: string) => {
return useQuery({
queryKey: ['getItems'],
queryFn: fetchItems,
queryFn: () => fetchItems(searchQuery || ''),
enabled
})
}
Expand Down
22 changes: 16 additions & 6 deletions src/components/CardItem.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,19 +9,29 @@ import {
import { Link } from 'react-router-dom';
import FavoriteFab from './FavoriteFab';
import type { IItem } from '../api/useGetItems';
import { useState } from 'react';

interface Props {
cardData: IItem;
}

const CardItem = ({ cardData }: Props) => {
const [showFab, setShowFab] = useState<boolean>(false);

return (
<Box position={'relative'} height={275}>
<FavoriteFab
itemId={cardData.item_id}
favorite={true}
size="small"
/>
<Box
position={'relative'}
height={275}
onMouseOver={() => setShowFab(true)}
onMouseOut={() => setShowFab(false)}
>
{showFab && (
<FavoriteFab
itemId={cardData.item_id}
favorite={true}
size="small"
/>
)}
<Card
variant="outlined"
sx={{
Expand Down
12 changes: 6 additions & 6 deletions src/components/Navbar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,7 @@ import { useAppContext } from '../App';
import useCartCount from '../hooks/useCartCount';

const Navbar = () => {
const { cartCount } = useAppContext();
const [searchQuery, setSearchQuery] = useState<string>('');
const { cartCount, setSearchQuery } = useAppContext();
const [anchorEl, setAnchorEl] = useState<null | HTMLElement>(null);
const open = Boolean(anchorEl);
const { isLoggedIn, logout, username, picture } = useLoginStore();
Expand Down Expand Up @@ -64,8 +63,6 @@ const Navbar = () => {

return (
<>
{/* TODO: Workaround until actual functionality is plugged in. */}
{<div hidden>{searchQuery}</div>}
<AppBar
position="sticky"
elevation={0}
Expand All @@ -84,7 +81,7 @@ const Navbar = () => {
backdropFilter: 'blur(24px)',
}}
>
<Link to="/">
<Link to="/" onClick={() => setSearchQuery('')}>
<Box
component="img"
mt={{ xs: 0, md: -1 }}
Expand All @@ -94,6 +91,9 @@ const Navbar = () => {
xs: `url(${LogoImage})`,
sm: `url(${Logo})`,
},
minWidth: {
xs: '50px',
},
maxHeight: '50px',
}}
alt="Etsify Logo"
Expand Down Expand Up @@ -141,7 +141,7 @@ const Navbar = () => {
src={picture}
></Avatar>
) : (
<Avatar>{username}</Avatar>
<Avatar>{username.charAt(0)}</Avatar>
)}
</IconButton>
) : (
Expand Down
2 changes: 1 addition & 1 deletion src/components/SearchBar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ const SearchBar = ({ setSearchQuery }: Props) => {
event.preventDefault();
console.log(searchString);
setSearchQuery(searchString);
setSearchString('');
//setSearchString('');
};

return (
Expand Down
26 changes: 10 additions & 16 deletions src/hooks/useCartCount.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,27 +3,21 @@ import axios from "axios";
import { useQuery } from "@tanstack/react-query";

function useCartCount() {
const { server, isInit, cartCount, setCartCount } = useAppContext();
const { server, setCartCount } = useAppContext();

useQuery({
queryKey: ['cartCount'],
queryFn: async () => {
if (server.authToken !== '') {
return axios.get(`${server.apiUrl}/api/carts/count`, {
headers: { Authorization: `Bearer ${server.authToken}` },
}).then(res => {
if (res.status === 200) {
setCartCount(res.data);
return res.data;
}
});
}
else {
setCartCount(0);
}
return cartCount;
return axios.get(`${server.apiUrl}/api/carts/count`, {
headers: { Authorization: `Bearer ${server.authToken}` },
}).then(res => {
if (res.status === 200) {
setCartCount(res.data);
return res.data;
}
});
},
enabled: isInit
enabled: server.isLoggedIn
});
}

Expand Down
1 change: 1 addition & 0 deletions src/pages/Cart.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ const CartItem = ({ refreshCart, removeItem, itemData }: Props) => {
<Card key={item.item_id} sx={{ padding: 2 }} variant="outlined">
<Typography display={'inline-flex'} component="div" mb={1}>
<Avatar
src={item.store.logo_url || ''}
children="SN"
sx={{
width: 30,
Expand Down
16 changes: 13 additions & 3 deletions src/pages/Home.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,21 @@ import { useAppContext } from '../App';
import useGetItems from '../api/useGetItems';
import type { IItem } from '../api/useGetItems';
import Grid from '@mui/material/Grid2';
import { useEffect } from 'react';

export const Home = () => {
const { isInit } = useAppContext();
const { isLoading, data: { items } = {} } = useGetItems(isInit);
const { isInit, searchQuery } = useAppContext();
const {
refetch,
isLoading,
data: { items } = {},
} = useGetItems(isInit, searchQuery);

if (!isLoading)
useEffect(() => {
refetch();
}, [searchQuery]);

if (!isLoading) {
return (
<Grid container spacing={2} px={1}>
{items?.map((item: IItem) => {
Expand All @@ -23,4 +32,5 @@ export const Home = () => {
})}
</Grid>
);
}
};

0 comments on commit 03869d8

Please sign in to comment.