64 lines
1.5 KiB
JavaScript
64 lines
1.5 KiB
JavaScript
"use client";
|
|
|
|
import authAxios, { backendUrl } from "@/utils/axios";
|
|
import axios from "axios";
|
|
import { createContext, useEffect, useState } from "react";
|
|
import toast from "react-hot-toast";
|
|
|
|
const ProductContext = createContext();
|
|
|
|
export const ProductContextProvider = ({ children }) => {
|
|
const [products, setProducts] = useState(null);
|
|
const [category, setCategory] = useState(null);
|
|
|
|
|
|
const fetchData = async () => {
|
|
const response = await axios.get(`${backendUrl}/products/variants/`);
|
|
setProducts(response.data)
|
|
};
|
|
|
|
const fetchCategory = async () => {
|
|
const response = await axios.get(`${backendUrl}/products/category/`);
|
|
setCategory(response.data);
|
|
|
|
};
|
|
useEffect(() => {
|
|
fetchData();
|
|
fetchCategory();
|
|
}, []);
|
|
|
|
const cartFn = async (variantId, designId, quantity, showToast = true) => {
|
|
|
|
try{
|
|
const response = await authAxios.post('/orders/cart/manage_item/',{
|
|
variant: variantId,
|
|
design: designId,
|
|
quantity: quantity
|
|
})
|
|
if (showToast) {
|
|
toast.success('Modified Cart Successfully!')
|
|
}
|
|
return response
|
|
}
|
|
catch(error){
|
|
if (error?.response.data?.detail) {
|
|
toast.error('Please login First!')
|
|
}
|
|
else {
|
|
toast.error(error?.response.data?.error || 'Failed To Modify Cart')
|
|
}
|
|
return error
|
|
}
|
|
}
|
|
return (
|
|
<ProductContext.Provider value={{
|
|
products,
|
|
cartFn,
|
|
category,
|
|
|
|
}}>{children}</ProductContext.Provider>
|
|
);
|
|
};
|
|
|
|
export default ProductContext;
|