-
Notifications
You must be signed in to change notification settings - Fork 128
Expand file tree
/
Copy pathProductContext.jsx
More file actions
42 lines (36 loc) · 1.11 KB
/
ProductContext.jsx
File metadata and controls
42 lines (36 loc) · 1.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import { createContext, useContext, useEffect, useState } from "react";
import productService from "services/product.service";
const ProductContext = createContext();
const ProductProvider = ({ children }) => {
const [products, setProducts] = useState(null);
const [isLoading, setIsLoading] = useState(false);
const [page, setPage] = useState(1);
useEffect(() => {
setIsLoading(true);
productService
.getProducts(page)
.then((response) => {
setProducts(response.data);
setIsLoading(false);
})
.catch((error) => {
console.log(error);
setIsLoading(false);
});
}, [page]);
return (
<ProductContext.Provider
value={{ products, setProducts, isLoading, setIsLoading, page, setPage }}
>
{children}
</ProductContext.Provider>
);
};
const useProduct = () => {
const context = useContext(ProductContext);
if (context === undefined) {
throw new Error("useProduct must be used within a ProductProvider");
}
return context;
};
export { ProductContext, ProductProvider, useProduct };