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

Add product to favourites #16

Merged
merged 7 commits into from
Sep 4, 2023
Merged
Show file tree
Hide file tree
Changes from 2 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
3 changes: 3 additions & 0 deletions src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
import { Outlet } from 'react-router';
import { Header } from './components/Header';
import { Footer } from './components/Footer';
import { useInitFavourites } from './hooks/useLocalStorage';

const App = () => {
useInitFavourites();

return (
<div>
<Header />
Expand Down
2 changes: 2 additions & 0 deletions src/Root.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import App from './App';
import CatalogPage from './pages/CatalogPage';
import NotFound from './pages/NotFound';
import ScrollToTop from './components/ScrollToTop';
import { FavouritesPage } from './pages/FavouritesPage';

export const Root = () => (
<BrowserRouter>
Expand All @@ -20,6 +21,7 @@ export const Root = () => (
<Route path="accessories">
<Route path=":accessoryId?" element={<h1>Accessories Page</h1>} />
</Route>
<Route path='favourites' element={<FavouritesPage />} />
<Route path="*" element={<NotFound />} />
</Route>
</Routes>
Expand Down
16 changes: 13 additions & 3 deletions src/components/Card.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,18 @@ import { FiHeart } from 'react-icons/fi';
import { Button } from './Button';
import { ProductProperties } from './ProductProperties';
import { IProduct } from '../types/Product';
import { useAppDispatch, useAppSelector } from '../redux';
import { toggleFavourite } from '../redux/slices/favouritesSlice';

type Props = {
product: IProduct;
};

export const Card = ({ product }: Props) => {
const favouriteItems = useAppSelector(state => state.favourites.favouriteItems);
const dispatch = useAppDispatch();
const [favorite, setFavorite] = useState(false);

const productProps = [
{
name: 'Screen',
Expand All @@ -26,7 +31,12 @@ export const Card = ({ product }: Props) => {
},
];

const handleClick = () => {
const hasProductId = (productId: string) => {
return favouriteItems.some(favouriteItem => favouriteItem._id === productId);
}; // See if the product id is in the favoriteItems array

const handleClick = (currentProduct: IProduct) => {
dispatch(toggleFavourite(currentProduct));
setFavorite(!favorite);
};

Expand Down Expand Up @@ -62,11 +72,11 @@ export const Card = ({ product }: Props) => {
'active:scale-95',
'flex justify-center items-center shrink-0 duration-300',
])}
onClick={handleClick}
onClick={() => handleClick(product)}
>
<FiHeart
className={classNames({
'text-secondary-accent': favorite,
'text-secondary-accent': hasProductId(product._id),
})}
/>
</button>
Expand Down
6 changes: 3 additions & 3 deletions src/components/Header.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -50,12 +50,12 @@ export const Header: React.FC = () => {

<div className="flex items-center justify-end">
<div className="border-l border-elements box-border">
<a
<NavLink
className="hover:shadow-lg duration-200 px-4 py-6 desktop:p-6 hidden tablet:flex"
href="/#"
to="/favourites"
>
<FiHeart />
</a>
</NavLink>
</div>
<div className="border-l border-elements box-border mx-0">
<a
Expand Down
10 changes: 10 additions & 0 deletions src/hooks/useLocalStorage.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { useEffect } from 'react';
import { getInitialFavourites, useAppDispatch } from '../redux/';

export const useInitFavourites = () => {
const dispatch = useAppDispatch();

useEffect(() => {
dispatch(getInitialFavourites());
}, []);
};
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

GJ, but, please, rename file to your hook name

41 changes: 23 additions & 18 deletions src/pages/FavouritesPage.tsx
Original file line number Diff line number Diff line change
@@ -1,26 +1,31 @@
import React, { useEffect, useState } from 'react';
// import React, { useEffect, useState } from 'react';
import React from 'react';
import { Card } from '../components/Card';
import axios from 'axios';
import { IProduct } from '../types/Product';
// import axios from 'axios';
// import { IProduct } from '../types/Product';
import { useAppSelector } from '../redux';

export const FavouritesPage: React.FC = () => {
// #region rewrite to Redux
const [products, setProducts] = useState<IProduct[]>([]);
const favouriteItems = useAppSelector(state => state.favourites.favouriteItems);

// eslint-disable-next-line no-console
// const [products, setProducts] = useState<IProduct[]>([]);
// #endregion

// #region rewrite to RTQ Query
useEffect(() => {
axios
.get('https://dreamteam.onrender.com/products', {
params: { page: 1, perPage: 8 },
})
.then((res) => {
setProducts(res.data.data);
})
.catch((e) => {
throw new Error(e);
});
}, []);
// useEffect(() => {
// axios
// .get('https://dreamteam.onrender.com/products', {
// params: { page: 1, perPage: 8 },
// })
// .then((res) => {
// setProducts(res.data.data);
// })
// .catch((e) => {
// throw new Error(e);
// });
// }, []);
// #endregion
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

please delete comments


return (
Expand All @@ -30,11 +35,11 @@ export const FavouritesPage: React.FC = () => {
FavouritesPage
</h1>
<p className="text-sm mb-8 tablet:mb-9 font-semibold leading-[21px] text-secondary">
5 items
{`${favouriteItems.length} items`}
</p>
</header>
<div className="grid grid-cols-1 gap-4 tablet:grid-cols-2 desktop:grid-cols-4">
{products.map((pr) => (
{favouriteItems.map((pr) => (
<Card product={pr} key={pr._id} />
))}
</div>
Expand Down
6 changes: 5 additions & 1 deletion src/redux/index.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,17 @@
import { configureStore } from '@reduxjs/toolkit';
import { TypedUseSelectorHook, useDispatch, useSelector } from 'react-redux';
import { favouritesSlice } from './slices/favouritesSlice';

const store = configureStore({
reducer: {},
reducer: {
[favouritesSlice.name]: favouritesSlice.reducer,
},
middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(),
});

export { store };

export * from './slices/favouritesSlice';
export type RootState = ReturnType<typeof store.getState>;
export type AppDispatch = typeof store.dispatch;
export const useAppDispatch = () => useDispatch<AppDispatch>();
Expand Down
39 changes: 39 additions & 0 deletions src/redux/slices/favouritesSlice.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import { createSlice } from '@reduxjs/toolkit';
import { IProduct } from '../../types/Product';

type InitialState = {
favouriteItems: IProduct[];
};

const initialState: InitialState = {
favouriteItems: [],
};

export const favouritesSlice = createSlice({
name: 'favourites',
initialState,
reducers: {
getInitialFavourites: (state) => {
state.favouriteItems = JSON.parse(
localStorage.getItem('favourite-items') || '[]',
) as IProduct[];
},
toggleFavourite: (state, action) => {
const hasProductId = state.favouriteItems.some(
(favouriteItem) => favouriteItem._id === action.payload._id,
);

if (hasProductId) {
state.favouriteItems = state.favouriteItems.filter(
(favouriteItem) => favouriteItem._id !== action.payload._id,
);
localStorage.setItem('favourite-items', JSON.stringify(state.favouriteItems));
} else {
state.favouriteItems.push(action.payload);
localStorage.setItem('favourite-items', JSON.stringify(state.favouriteItems));
}
},
},
});

export const { toggleFavourite, getInitialFavourites } = favouritesSlice.actions;