· 5 years ago · Feb 19, 2021, 05:48 PM
1import React, { useState, useEffect } from "react"
2import { Link } from "gatsby"
3
4import Datatable from "../components/datatable"
5
6// Fetching data
7require("es6-promise").polyfill();
8require("isomorphic-fetch")
9
10const IndexPage = () => {
11 const [data, setData] = useState([]);
12 const [q, setQ] = useState("");
13 const [totalRows, setTotalRows] = useState("Loading...");
14 const [displayedRows, setdisplayedRows] = useState("")
15
16 function updateTotalRows (num) {
17 setTotalRows(num)
18 }
19
20 function updateDisplayedRows (num) {
21 setdisplayedRows(num)
22 }
23
24 // transform JSON
25 function renameKey ( obj, oldKey, newKey ) {
26 obj[newKey] = obj[oldKey];
27 delete obj[oldKey];
28 }
29
30 function deleteKey (obj, key) {
31 delete obj[key]
32 }
33
34 useEffect(() => {
35 // Change when API in production
36 fetch("http://localhost:8080/api/tests")
37 .then((response) => response.json())
38 .then((json) => {
39
40 // set data in state
41 updateTotalRows(json.length)
42 updateDisplayedRows(json.length)
43 setData(json)
44 })
45
46 }, []);
47
48 function search(rows){
49 const columns = rows[0] && Object.keys(rows[0]);
50 let output = rows.filter(
51 (row) =>
52 columns.some(column => row[column].toString().toLowerCase().indexOf(q.toLowerCase()) > -1)
53 );
54 console.log(output.length); // works
55 updateDisplayedRows(output.length); // causes infinite loop error
56 return output
57 }
58
59 return (
60 <Layout>
61 <h1>Active Tests: {totalRows}</h1>
62 <p> Showing {displayedRows} of {totalRows} </p>
63 <input type="text" value={q} onChange={(e) => setQ(e.target.value)}/>
64 <Datatable data={search(data)} />
65 </Layout>
66 );
67}
68
69
70export default IndexPage