Skip to content

Instantly share code, notes, and snippets.

@TheAlchemistKE
Created November 8, 2023 13:13
Show Gist options
  • Save TheAlchemistKE/252e27024f63f85131840ae1496f6146 to your computer and use it in GitHub Desktop.
Save TheAlchemistKE/252e27024f63f85131840ae1496f6146 to your computer and use it in GitHub Desktop.
"use client";
import React, { useEffect, useRef, useState } from "react";
import ReactToPrint from "react-to-print";
import { Button } from "./ui/button";
import Receipt from "./receipt";
import { scanCard } from "@/lib/client";
import { useToast } from "./ui/use-toast";
export default function PrintComponent() {
let componentRef = useRef();
let printRef = useRef();
const [isLoading, setIsLoading] = useState(true);
const [barcode, setBarcode] = useState("");
const [attendance, setAttendance] = useState();
const [success, setSuccess] = useState(false);
const toast = useToast();
useEffect(() => {
if (attendance) {
printRef.current.handlePrint();
}
}, [attendance]);
const onSubmit = async (event: any, barcode: string) => {
if (event.key === "Enter") {
const attendanceData: any = await scanCard(barcode);
if (attendanceData) {
setAttendance(attendanceData.data);
setIsLoading(false);
setSuccess(true)
toast.toast({
title: "Record Lunch Attendance",
description: attendanceData.message,
});
} else {
setSuccess(false)
setBarcode("")
}
}
};
// @ts-ignore
return (
<>
<div className="">
<input
type="text"
name=""
id=""
className="w-[350px] px-4 py-2 border rounded-lg focus:outline-none focus:border-blue-500 transition duration-300 ease-in-out"
placeholder="Enter Barcode and press Enter"
value={barcode}
onChange={(e: any) => {
setBarcode(e.currentTarget.value);
}}
onKeyUp={(event) => {
onSubmit(event, barcode);
}}
/>
{isLoading ? (
<p className="semibold mt-2 pl-2">Please enter your barcode</p>
) : (
<ReactToPrint
trigger={() => <Button className="hidden">Print this out!</Button>}
content={() => componentRef}
documentTitle={`Receipt ${attendance?.staff_name}`}
ref={printRef}
/>
)}
<div className="hidden">
<Receipt
ref={(el) => (componentRef = el)}
success={success}
barcode={attendance?.barcode || ""}
name={attendance?.staff_name || ""}
/>
</div>
</div>
</>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment