Skip to content

Commit

Permalink
refactor: Integrate backend API for wishlist
Browse files Browse the repository at this point in the history
  • Loading branch information
chhakuli123 committed May 27, 2023
1 parent 999a56f commit ea5fdd0
Showing 1 changed file with 53 additions and 3 deletions.
56 changes: 53 additions & 3 deletions src/context/wishlistContext.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,21 @@
import { createContext, useReducer, useContext } from "react";
import React, { createContext, useReducer, useContext } from "react";

import { wishlistReducer } from "reducer";
import {
ADD_TO_WISHLIST,
REMOVE_FROM_WISHLIST,
SET_WISHLIST,
addToWishlist,
getWishlist,
removeFromWishlist,
} from "utils";
import { useAuth } from "./authContext";

const WishlistContext = createContext();

const WishlistContextProvider = ({ children }) => {
const { token } = useAuth();

// Set the initial state for the wishlist context
const initialState = {
wishlist: [],
Expand All @@ -15,8 +27,46 @@ const WishlistContextProvider = ({ children }) => {
initialState
);

const fetchWishlist = async () => {
try {
const response = await getWishlist(token);
const { data } = response;
wishlistDispatch({ type: SET_WISHLIST, payload: data.wishlist });
} catch (error) {
console.error("Fetch Wishlist Error:", error);
}
};

const addToWishlistHandler = async (product) => {
try {
await addToWishlist(token, product);
wishlistDispatch({
type: ADD_TO_WISHLIST,
payload: product,
});
} catch (error) {
console.log(error);
}
};

const removeFromWishlistHandler = async (productId) => {
try {
await removeFromWishlist(token, productId);
wishlistDispatch({ type: REMOVE_FROM_WISHLIST, payload: productId });
} catch (error) {
console.log(error);
}
};

return (
<WishlistContext.Provider value={{ wishlistState, wishlistDispatch }}>
<WishlistContext.Provider
value={{
wishlistState,
fetchWishlist,
addToWishlistHandler,
removeFromWishlistHandler,
}}
>
{children}
</WishlistContext.Provider>
);
Expand All @@ -25,4 +75,4 @@ const WishlistContextProvider = ({ children }) => {
// Custom hook to consume the WishlistContext
const useWishlist = () => useContext(WishlistContext);

export { useWishlist, WishlistContextProvider };
export { WishlistContextProvider, useWishlist };

0 comments on commit ea5fdd0

Please sign in to comment.