Skip to content

Instantly share code, notes, and snippets.

@mskog
Created January 8, 2020 09:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mskog/228fc3806bdfc3c5fd6f87823be9a1bb to your computer and use it in GitHub Desktop.
Save mskog/228fc3806bdfc3c5fd6f87823be9a1bb to your computer and use it in GitHub Desktop.
shop.js
import React, { useEffect, useState } from "react";
import Product from "./shop/product";
import "./shop.css";
const Shop = () => {
const url = "http://localhost:3000/graphql";
const data = {
query: `query {
broadbandProducts(first: 4) {
id
bandwidthHuman
technology
state
}
}`
};
const [products, updateProducts] = useState({ broadbandProducts: [] });
useEffect(() => {
async function fetchData() {
try {
const response = await fetch(url, {
method: "POST",
body: JSON.stringify(data),
headers: {
"Content-Type": "application/json",
"X-User-AuthenticationKey": process.env.USER_KEY, //
"X-User-Token": process.env.USER_TOKEN //
}
});
const responseJson = await response.json();
// eslint-disable-next-line no-console
console.log("Success");
updateProducts(responseJson.data);
} catch (error) {
// eslint-disable-next-line no-console
console.error("Error:", error);
}
}
fetchData();
}, []);
const [cart, updateCart] = useState([]);
const [displayMessage, setDisplayMessage] = useState(false);
const [timer, setTimer] = useState();
const addedToCart = clickEvent => {
const product = clickEvent.currentTarget.dataset.name;
updateCart(product);
setDisplayMessage(true);
clearTimeout(timer);
setTimer(
setTimeout(() => {
setDisplayMessage(false);
}, 5000)
);
return () => clearTimeout(timer);
};
const popupItem = () => {
return (
<div className="cart-popup-message">
{cart} har lagts till i varukorgen
</div>
);
};
return (
<div className="shop">
<div className="cart-popup">
{displayMessage === true ? popupItem() : null}
</div>
<div className="shop-grid">
{products.broadbandProducts.map(product => (
<Product
product_id={product.id}
product_name={product.bandwidthHuman}
product_technology={product.technology}
addToCart={addedToCart}
/>
))}
</div>
</div>
);
};
export default Shop;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment