Skip to content

Commit

Permalink
Add persist modal form data
Browse files Browse the repository at this point in the history
  • Loading branch information
ahmetcan-7 committed May 20, 2023
1 parent 49c4718 commit f53892c
Show file tree
Hide file tree
Showing 5 changed files with 101 additions and 38 deletions.
1 change: 1 addition & 0 deletions src/components/Comments/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ function Comments({ comments, onCreateComment }: CommentsProps) {
display: "flex",
alignItems: "center",
justifyContent: "space-between",
marginTop: "2rem",
}}
>
<Typography variant="h4" component="h2" style={{ marginLeft: "1rem" }}>
Expand Down
3 changes: 3 additions & 0 deletions src/components/Modal/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ interface ModalProps {
title: string;
disableBtn?: boolean;
children: React.ReactNode;
onClose?: () => void;
}
export default function Modal({
open,
Expand All @@ -21,9 +22,11 @@ export default function Modal({
title,
disableBtn = false,
children,
onClose,
}: ModalProps) {
const handleClose = () => {
setOpen(false);
onClose?.();
};

const handleOpen = () => {
Expand Down
86 changes: 76 additions & 10 deletions src/pages/Cart/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,14 @@ import { showSuccess } from "../../utils/showSuccess";
import { ProductApi } from "../../api/productApi";
import { showError } from "../../utils/showError";
import { LoadingButton } from "@mui/lab";
import { useSearchParams } from "react-router-dom";

function Cart() {
const [searchParams, setSearchParams] = useSearchParams();
const items = useSelector((state: AppState) => state.cart);
const [modalOpen, setModalOpen] = useState(false);
const [modalOpen, setModalOpen] = useState(
searchParams.get("order") === "true"
);
const [districts, setDistricts] = useState([]);
const dispatch = useDispatch<any>();
const form = useFormik({
Expand All @@ -43,17 +47,24 @@ function Cart() {

const openModal = () => {
setModalOpen(true);
setSearchParams({
order: "true",
});
};

const closeModal = () => {
setModalOpen(false);
setSearchParams({
order: "false",
});
form.resetForm();
};

const createMutation = useMutation(OrderApi.createOrder, {
onSuccess: () => {
showSuccess("Order has been created successfully");
form.resetForm();
dispatch(clearAllItems());
closeModal();
},
onError: (e: any) => {
const res = e.response?.data?.message as string;
Expand Down Expand Up @@ -82,7 +93,67 @@ function Cart() {
showError(`${productNames} not in stock!`);
};

console.log("loading", createMutation.isLoading);
/*
// - Cache Api example
function saveFormDataToCache(formData: any) {
if ("caches" in window) {
caches.open("formCache").then((cache) => {
const request = new Request("form-data", {
method: "GET",
});
const response = new Response(JSON.stringify(formData));
cache.put(request, response).then(() => {
console.log("Data updated in cache");
});
});
}
}
function loadFormDataFromCache() {
return new Promise((resolve, reject) => {
if ("caches" in window) {
caches.open("formCache").then((cache) => {
cache.match("form-data").then((response) => {
if (response) {
response.json().then((data) => {
resolve(data);
form.setValues(data);
console.log("gelen data", data);
});
} else {
reject(new Error("Form data not found in cache."));
}
});
});
} else {
reject(new Error("Cache API is not supported."));
}
});
}
useEffect(() => {
loadFormDataFromCache();
}, []);
useEffect(() => {
saveFormDataToCache(form.values);
}, [form]);
*/

useEffect(() => {
const savedFormData = sessionStorage.getItem("cart_form");
if (savedFormData) {
form.setValues(JSON.parse(savedFormData));
}
}, []);

useEffect(() => {
sessionStorage.setItem("cart_form", JSON.stringify(form.values));
}, [form]);

return (
<>
Expand All @@ -102,6 +173,7 @@ function Cart() {
setOpen={setModalOpen}
title="Please enter your informations"
disableBtn={true}
onClose={closeModal}
>
<form onSubmit={form.handleSubmit}>
<SelectInput name="city" label="city" form={form} data={cities} />
Expand All @@ -120,13 +192,7 @@ function Cart() {
>
Cancel
</Button>
<Button
color="primary"
variant="contained"
fullWidth
type="submit"
onClick={closeModal}
>
<Button color="primary" variant="contained" fullWidth type="submit">
Order
</Button>
</form>
Expand Down
2 changes: 1 addition & 1 deletion src/pages/Products/Product/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ function Product() {

return (
<>
<Container maxWidth="md">
<Container maxWidth="md" style={{ marginTop: "1rem" }}>
<ProductCard product={product} />
</Container>
</>
Expand Down
47 changes: 20 additions & 27 deletions src/pages/Products/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { useInView } from "react-intersection-observer";
import { ProductApi } from "../../api/productApi";
import { PRODUCT_PARAM } from "../../constants/product";
import Card from "../../components/Card";
import { Grid, Typography } from "@material-ui/core";
import { Grid } from "@material-ui/core";
import SearchBar from "../../components/SearchBar";
import { CategoryApi } from "../../api/categoryApi";
import { Category } from "../../types/category";
Expand All @@ -21,35 +21,28 @@ function Products() {
const [categories, setCategories] = useState<Category[]>([]);

const [searchTerm, setSearchTerm] = useState("");
// const searchTerm = searchValue.length >= 3 ? searchValue : "";

const {
status,
data,
isFetching,
isFetchingNextPage,
fetchNextPage,
hasNextPage,
} = useInfiniteQuery(
["projects", searchTerm, sortBy, filter],
({ pageParam = 0 }) =>
ProductApi.getProducts({
...PRODUCT_PARAM,
page: pageParam,
searchTerm: searchTerm,
sort: sortBy,
filter: filter,
}),
{
getNextPageParam: (lastGroup, allGroups) => {
const morePageExist = lastGroup?.length === PRODUCT_PARAM.size;
const { data, isFetching, isFetchingNextPage, fetchNextPage, hasNextPage } =
useInfiniteQuery(
["projects", searchTerm, sortBy, filter],
({ pageParam = 0 }) =>
ProductApi.getProducts({
...PRODUCT_PARAM,
page: pageParam,
searchTerm: searchTerm,
sort: sortBy,
filter: filter,
}),
{
getNextPageParam: (lastGroup, allGroups) => {
const morePageExist = lastGroup?.length === PRODUCT_PARAM.size;

if (!morePageExist) return;
if (!morePageExist) return;

return allGroups?.length;
},
}
);
return allGroups?.length;
},
}
);

useEffect(() => {
if (inView) {
Expand Down

0 comments on commit f53892c

Please sign in to comment.