-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
54 lines (46 loc) · 1.42 KB
/
index.js
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
43
44
45
46
47
48
49
50
51
52
53
54
import React, { useState, useContext, useEffect } from "react";
import { getCoffeeData } from "../api/getData";
import Layout from "../components/Layout";
import Loading from "../components/Loading";
import ItemGroup from "../components/ItemGroup";
import Cart from "../components/Cart";
import { GlobalContext } from "../components/GlobalStateProvider";
// this should be a reducer
function useCoffeeData() {
const [data, setData] = useState();
const [loading, setLoading] = useState(true);
const [error, setError] = useState();
useEffect(() => {
const getData = async () => {
try {
const newData = await getCoffeeData();
setData(newData);
setLoading(false);
} catch (ex) {
setData(undefined);
setLoading(false);
setError(ex);
}
};
getData();
}, []);
return { data, isLoading: loading, error };
}
export default function() {
const { data, isLoading, error } = useCoffeeData();
const [showCart, setShowCart] = useState(false);
const { dispatch } = useContext(GlobalContext);
return (
<Layout onToggleCart={() => setShowCart(!showCart)} showCart={showCart}>
{isLoading && <Loading />}
{showCart && <Cart />}
{!showCart && data && (
<ItemGroup
data={data}
addToCart={item => dispatch({ type: "ADD_ITEM", payload: item })}
/>
)}
{error && JSON.stringify(error)}
</Layout>
);
}