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 5 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
2 changes: 2 additions & 0 deletions src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import { Outlet } from 'react-router';
import { Header } from './components/Header';
import { Footer } from './components/Footer';
import { useInitFavourites } from './hooks/useInitFavourites';
import { useInitialCart } from './hooks/useInitialCart';

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

return (
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';
import { CartPage } from './pages/CartPage';

export const Root = () => (
Expand All @@ -21,6 +22,7 @@ export const Root = () => (
<Route path="accessories">
<Route path=":accessoryId?" element={<h1>Accessories Page</h1>} />
</Route>
<Route path='favourites' element={<FavouritesPage />} />
<Route path='cart' element={<CartPage /> } />
<Route path="*" element={<NotFound />} />
</Route>
Expand Down
12 changes: 8 additions & 4 deletions src/components/Card.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,17 @@ import { addItemToCart, useAppDispatch } from '../redux';
import { Button } from './Button';
import { ProductProperties } from './ProductProperties';
import { IProduct } from '../types/Product';
import { useAppDispatch } from '../redux';
import { toggleFavourite } from '../redux/slices/favouritesSlice';

type Props = {
product: IProduct;
};

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

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

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

Expand Down Expand Up @@ -68,11 +72,11 @@ export const Card = ({ product }: Props) => {
'active:scale-95',
'flex justify-center items-center shrink-0 duration-300',
])}
onClick={handleAddToFav}
onClick={() => handleToggleFav(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">
<NavLink
Expand Down
10 changes: 10 additions & 0 deletions src/hooks/useInitFavourites.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());
}, []);
};
28 changes: 5 additions & 23 deletions src/pages/FavouritesPage.tsx
Original file line number Diff line number Diff line change
@@ -1,27 +1,9 @@
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 { useAppSelector } from '../redux';

export const FavouritesPage: React.FC = () => {
// #region rewrite to Redux
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);
});
}, []);
// #endregion
const favouriteItems = useAppSelector(state => state.favourites.favouriteItems);

return (
<main className="container mx-auto flex flex-col items-center tablet:items-start px-4 pt-6 tablet:px-6 desktop:w-[1200px]">
Expand All @@ -30,11 +12,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
3 changes: 3 additions & 0 deletions src/redux/index.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,19 @@
import { configureStore } from '@reduxjs/toolkit';
import { TypedUseSelectorHook, useDispatch, useSelector } from 'react-redux';
import { favouritesSlice } from './slices/favouritesSlice';
import { cartSlice } from './slices/cartSlice';

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

export { store };

export * from './slices/favouritesSlice';
export * from './slices/cartSlice';
export type RootState = ReturnType<typeof store.getState>;
export type AppDispatch = typeof store.dispatch;
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;
Loading