import React, { useEffect, useState } from "react";
// Define a type for your data
type UserData = {
[key: string]: string | string[];
};
type UserEntry = {
[key: string]: string | string[] | undefined; // Adjust this based on your data
structure
};
const Home = () => {
const [userInfo, setUserInfo] = useState<UserData[]>([]);
const [searchTerm, setSearchTerm] = useState<string>('');
useEffect(() => {
const getData = async () => {
try {
const query = await
fetch('https://script.google.com/macros/s/AKfycbwsr_mdDkyb1UPQ9YOjKQfd1Hv0jEg0azpDL
E5gIJHOgwQX9E-IKd2Qzc6FhzChjAPDDg/exec');
const response = await query.json();
console.log('response from API', response);
setUserInfo(response);
} catch (error) {
console.error('Error fetching data:', error);
}
};
// Fetch data initially
getData();
// Set up an interval to fetch data every 5 seconds (adjust as needed)
const intervalId = setInterval(() => {
getData();
}, 5000);
// Clean up the interval when the component is unmounted
return () => clearInterval(intervalId);
}, []); // The empty dependency array ensures that the effect runs only once on
mount
// Filter the data based on the search term
const filteredData = userInfo.filter((user) =>
Object.values(user).some((value) =>
Array.isArray(value) ? value.join(",
").toLowerCase().includes(searchTerm.toLowerCase()) :
value.toLowerCase().includes(searchTerm.toLowerCase())
)
);
// Sort the filtered data based on the time
const sortedData = filteredData.sort((a, b) => {
const getTime = (value: string | string[]) => {
if (Array.isArray(value)) {
return value.length > 0 ? new Date(value[0]).getTime() : 0;
}
return new Date(value).getTime();
};
const timeA = getTime(a.time);
const timeB = getTime(b.time);
return timeB - timeA;
});
// Function to send itemNumber data back to the API
const sendItemNumberToAPI = async (itemNumber: number) => {
try {
// Send the itemNumber data back to the API
await
fetch('https://script.google.com/macros/s/AKfycbx95ofBq_I6cbzkJ0S4XF9DVmmrooUwm_jfT
42yoKDvA0DLwUNjWdPNie1MMvQ03XmTKA/exec', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
itemNumber: itemNumber,
}),
});
console.log(`ItemNumber ${itemNumber} sent back to the API successfully.`);
} catch (error) {
console.error('Error sending itemNumber to API:', error);
}
};
return (
<div style={{ padding: "10px", border: "1px solid #ccc", borderRadius: "5px",
margin: "10px" }}>
<h1>ChipMonkey database</h1>
{/* Search bar */}
<input
type="text"
placeholder="Search by phone or customer info"
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
style={{ marginBottom: "10px", padding: "5px" }}
/>
{/* Display sorted data */}
{sortedData.length > 0 ? (
sortedData.map((user: UserEntry, index: number) => {
// Find the original index in the userInfo array
const originalIndex = userInfo.findIndex((entry) => entry.time ===
user.time);
// Skip the entry with the original index 0 (demo entry)
if (originalIndex === 0) {
return null;
}
// Adjust item number to start from 1
const itemNumber = originalIndex !== -1 ? originalIndex : index;
return (
<div key={index} style={{ border: "1px solid #ddd", borderRadius:
"5px", padding: "10px", margin: "10px 0" }}>
<h4>Token Number {itemNumber}</h4>
{Object.entries(user).map(([key, value]) => (
<p key={key}>
<strong>{key}:</strong> {Array.isArray(value) ? value.join(",
") : value}
</p>
))}
{/* Add a button to send itemNumber data back to the API */}
</div>
);
})
) : (
<p>No matching data found.</p>
)}
</div>
);
};
export default Home;