Use React Query for data loading
This commit is contained in:
26
src/App.tsx
26
src/App.tsx
@@ -1,24 +1,26 @@
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import * as d3 from "d3";
|
||||
import { useEffect, useState } from "react";
|
||||
import Legend from "./components/Legend";
|
||||
import QRCode from "./components/QRCode";
|
||||
import { QuestionGroupChart } from "./components/QuestionGroupChart";
|
||||
import { config } from "./config";
|
||||
import { CategoryMetadata, fetchCategoryMetadata } from "./lib/metadata";
|
||||
import { fetchGoogleSheet, ResponseData } from "./lib/parser";
|
||||
import { getSampleData } from "./lib/data";
|
||||
import { fetchCategoryMetadata } from "./lib/metadata";
|
||||
|
||||
function App() {
|
||||
const [data, setData] = useState<ResponseData[]>([]);
|
||||
const [categoryMetadata, setCategoryMetadata] = useState<CategoryMetadata[]>(
|
||||
[]
|
||||
);
|
||||
const { data: categoryMetadata } = useQuery({
|
||||
queryKey: ["categoryMetadata"],
|
||||
queryFn: fetchCategoryMetadata,
|
||||
});
|
||||
const { data, isPending, isError } = useQuery({
|
||||
queryKey: ["responses"],
|
||||
queryFn: getSampleData,
|
||||
refetchInterval: 2 * 1000, // Refresh every 5 seconds
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
fetchGoogleSheet().then(setData);
|
||||
// setData(getSampleData());
|
||||
|
||||
fetchCategoryMetadata().then(setCategoryMetadata);
|
||||
}, []);
|
||||
if (isPending) return <div>Loading...</div>;
|
||||
if (isError) return <div>Error loading data</div>;
|
||||
|
||||
if (!data.length) return null;
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { ResponseData } from "./parser";
|
||||
|
||||
export function getSampleData(): ResponseData[] {
|
||||
export function getSampleData(): Promise<ResponseData[]> {
|
||||
const questions = [
|
||||
"Service Quality",
|
||||
"Value for Money",
|
||||
@@ -24,5 +24,8 @@ export function getSampleData(): ResponseData[] {
|
||||
});
|
||||
}
|
||||
});
|
||||
return sampleData;
|
||||
// Simulate a delay to mimic fetching actual data
|
||||
return new Promise<ResponseData[]>((resolve) => {
|
||||
setTimeout(() => resolve(sampleData), 500);
|
||||
});
|
||||
}
|
||||
|
||||
11
src/main.tsx
11
src/main.tsx
@@ -1,10 +1,19 @@
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { ReactQueryDevtools } from "@tanstack/react-query-devtools";
|
||||
import { StrictMode } from "react";
|
||||
import { createRoot } from "react-dom/client";
|
||||
|
||||
import App from "./App";
|
||||
|
||||
import "./styles/index.scss";
|
||||
|
||||
const queryClient = new QueryClient();
|
||||
|
||||
createRoot(document.getElementById("root")!).render(
|
||||
<StrictMode>
|
||||
<App />
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<ReactQueryDevtools />
|
||||
<App />
|
||||
</QueryClientProvider>
|
||||
</StrictMode>
|
||||
);
|
||||
|
||||
Reference in New Issue
Block a user