Skip to content

local storage #65

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

61 changes: 60 additions & 1 deletion src/Components/Cart.jsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,67 @@
import { Dialog, Transition } from "@headlessui/react";
import { XIcon } from "@heroicons/react/outline";
import React, { Fragment } from "react";
import React, { Fragment, useEffect, useState } from "react";

/* const useLocalStorage = (storageKey, fallbackState) => {
const [value, setValue] = useState(
JSON.parse(localStorage.getItem(storageKey)) ?? fallbackState
);
useEffect(() => {
localStorage.setItem(storageKey, JSON.stringify(value));
}, [value, storageKey]);

return [value, setValue];
} */

export default function Cart({ open, setOpen, cart, updateCart }) {
/* const [localCart, setLocalCart] = useLocalStorage('localCart', cart)



useEffect(() => {
if (localCart) {
console.log(localCart)
cart = localCart
console.log(cart)
}
}, [])

useEffect(() => {
setLocalCart(cart)
}, [cart]);
*/



/* useEffect(() => {
if (cart.length <= 0 && localCart != null) {
setLocalCart(localCart)
} else if (cart.length != 0) {
setLocalCart(cart)
}
}, [cart]); */

/* const jsonArray = JSON.stringify(cart)

localStorage.setItem('cart', jsonArray)

const str = localStorage.getItem('cart')

const parsedArray = JSON.parse(str)

console.log(parsedArray) */

/* if (localStorage.getItem('cart')===null) {
let jsonArray = JSON.stringify(cart)
localStorage.setItem('cart', jsonArray)
} else {
let str = localStorage.getItem('cart')
cart = JSON.parse(str)

}

console.log(cart) */

return (
<Transition.Root show={open} as={Fragment}>
<Dialog
Expand Down
35 changes: 29 additions & 6 deletions src/Components/ProductFilters.jsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,21 @@
import { Disclosure, Menu, Transition } from "@headlessui/react";
import { ChevronDownIcon, FilterIcon } from "@heroicons/react/solid";
import React, { Fragment } from "react";
import React, { Fragment ,useState} from "react";



function classNames(...classes) {
return classes.filter(Boolean).join(" ");
}

export default function ProductFilters({ filterOptions, setFilterOptions, sortOptions, setSortOptions }) {


export default function ProductFilters({ filterOptions, setFilterOptions, sortOptions, setSortOptions,checkedPriceState,handleCheckboxPriceChange,checkedColorState,handleCheckboxColorChange }) {
const countCheckedBoxes = () =>{
return checkedPriceState.filter(Boolean).length+checkedColorState.filter(Boolean).length;
}


return (
<Disclosure
as="section"
Expand All @@ -24,7 +33,7 @@ export default function ProductFilters({ filterOptions, setFilterOptions, sortOp
className="flex-none w-5 h-5 mr-2 text-gray-400 group-hover:text-gray-500"
aria-hidden="true"
/>
0 Filters
{countCheckedBoxes()} Filters
</Disclosure.Button>
</div>
<div className="pl-6">
Expand All @@ -48,8 +57,14 @@ export default function ProductFilters({ filterOptions, setFilterOptions, sortOp
defaultValue={option.minValue}
type="checkbox"
className="flex-shrink-0 h-4 w-4 border-gray-300 rounded text-black focus:ring-black"
defaultChecked={option.checked}
//defaultChecked={option.checked}
checked={checkedPriceState[optionIdx]}
onChange={()=> handleCheckboxPriceChange(optionIdx)}



/>

<label htmlFor={`price-${optionIdx}`} className="ml-3 min-w-0 flex-1 text-gray-600">
{option.label}
</label>
Expand All @@ -68,7 +83,9 @@ export default function ProductFilters({ filterOptions, setFilterOptions, sortOp
defaultValue={option.value}
type="checkbox"
className="flex-shrink-0 h-4 w-4 border-gray-300 rounded text-black focus:ring-black"
defaultChecked={option.checked}
//defaultChecked={option.checked}
checked={checkedColorState[optionIdx]}
onChange={()=> handleCheckboxColorChange(optionIdx)}
/>
<label htmlFor={`color-${optionIdx}`} className="ml-3 min-w-0 flex-1 text-gray-600">
{option.label}
Expand Down Expand Up @@ -108,8 +125,14 @@ export default function ProductFilters({ filterOptions, setFilterOptions, sortOp
<Menu.Item key={option.name}>
{({ active }) => (
<button
onClick={() => {
onClick={(e) => {
// TODO
// setSortOptions=e.currentTarget.textContent;
//setSortOptions(...sortOptions.map((option)=>{if (option.name === e.currentTarget.textContent){option.current=true}}))
setSortOptions(state => state.map(s => s.name === e.currentTarget.textContent ? { ...s, current: true } : { ...s, current: false }))

console.log(sortOptions)

}}
className={classNames(
option.current ? "font-medium text-gray-900" : "text-gray-500",
Expand Down
80 changes: 76 additions & 4 deletions src/Components/ProductTable.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,34 +20,100 @@ const getDefaultFilterOptions = () => {
};
};



const getDefaultSortOptions = () => {
return [
{ name: "Price", current: false },
{ name: "Newest", current: false },
];
};

let bubbleSortDescPrice = (products) => {

for (var i = 0; i <= products.length - 1; i++) {
for (var j = 0; j < (products.length - i - 1); j++) {
if (products[j].price > products[j + 1].price) {
var temp = products[j]
products[j] = products[j + 1]
products[j + 1] = temp
}
}
}

};

let bubbleSortDescDate = (products) => {

for (var i = 0; i <= products.length - 1; i++) {
for (var j = 0; j < (products.length - i - 1); j++) {
if (products[j].releaseDate > products[j + 1].releaseDate) {
var temp = products[j]
products[j] = products[j + 1]
products[j + 1] = temp
}
}
}

};




export default function ProductTable({ cart, updateCart }) {
let [products, setProducts] = useState([]);

const [filterOptions, setFilterOptions] = useState(getDefaultFilterOptions());
const [sortOptions, setSortOptions] = useState(getDefaultSortOptions());

const [checkedPriceState,setCheckedPriceState] = useState(filterOptions.price.map((option) => (option.checked)));
const [checkedColorState,setCheckedColorState] = useState(filterOptions.color.map((option) => (option.checked)));


useEffect(() => {
let fetchProducts = async () => {
console.info("Fetching Products...");
let res = await fetch("http://localhost:3001/products");
let body = await res.json();
//console.log('>>>>'+sortOptions.name)
if (sortOptions[0].current === true) { // need to map and && price or newest
bubbleSortDescPrice(body)
setProducts(body);

} else if (sortOptions[1].current === true) {
bubbleSortDescDate(body)
setProducts(body)

}
setProducts(body);
};
fetchProducts();
});
}, [sortOptions[0].current]);

const handleCheckboxPriceChange = (index) => {
const updatedCheckedState = checkedPriceState.map((item, idx) =>
idx === index ? !item : item
);
setCheckedPriceState(updatedCheckedState);
};

const handleCheckboxColorChange = (index) => {
const updatedCheckedState = checkedColorState.map((item, idx) =>
idx === index ? !item : item
);
setCheckedColorState(updatedCheckedState);
};


return (
<div className="bg-white">
<div className="max-w-2xl mx-auto px-4 sm:px-6 lg:max-w-7xl lg:px-8">
<h2 className="sr-only">Products</h2>
<ProductFilters {...{ filterOptions, setFilterOptions, sortOptions, setSortOptions }} />
<ProductFilters {...{ filterOptions, setFilterOptions, sortOptions, setSortOptions }}
checkedPriceState={checkedPriceState}
handleCheckboxPriceChange={handleCheckboxPriceChange}
checkedColorState={checkedColorState}
handleCheckboxColorChange={handleCheckboxColorChange}/>

<div className="grid grid-cols-1 gap-y-10 sm:grid-cols-2 gap-x-6 lg:grid-cols-3 xl:grid-cols-4 xl:gap-x-8">
{products.map((product) => (
Expand All @@ -62,9 +128,14 @@ export default function ProductTable({ cart, updateCart }) {
type="button"
className="hidden group-hover:block group-hover:opacity-50 border border-transparent text-base font-medium rounded-md shadow-sm text-white bg-black"
onClick={() => {

let newCart = cart.slice();

if (!newCart.includes(product)) {



// console.log(product.id)
// console.log[cart[0]?.id]
if (!newCart.some(({id})=> id === product.id)) {
product.quantity = 1;
newCart.push(product);
} else {
Expand All @@ -85,6 +156,7 @@ export default function ProductTable({ cart, updateCart }) {
<p className="mt-1 text-lg font-medium text-gray-900">${product.price}</p>
</a>
))}

</div>
</div>
</div>
Expand Down
18 changes: 16 additions & 2 deletions src/Pages/Home.jsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,25 @@
import React, { useState } from "react";
import React, { useState,useEffect } from "react";
import Cart from "../Components/Cart";
import NavBar from "../Components/NavBar";
import ProductTable from "../Components/ProductTable";

const useLocalStorage = (storageKey, fallbackState) => {
const [value, setValue] = useState(
JSON.parse(localStorage.getItem(storageKey)) ?? fallbackState
);
useEffect(() => {
localStorage.setItem(storageKey, JSON.stringify(value));
}, [value, storageKey]);

return [value, setValue];
};

function Home() {
const [open, setOpen] = useState(false);
const [cart, updateCart] = useState([]);
const [cart, updateCart] = useLocalStorage('localCart', []);




return (
<main>
Expand Down