Skip to content

Instantly share code, notes, and snippets.

@johndavidsimmons
Created February 19, 2021 17:40
Show Gist options
  • Select an option

  • Save johndavidsimmons/c8219bffb3cbee4c4622828852f61b51 to your computer and use it in GitHub Desktop.

Select an option

Save johndavidsimmons/c8219bffb3cbee4c4622828852f61b51 to your computer and use it in GitHub Desktop.
import React, { useState, useEffect } from "react"
import { Link } from "gatsby"
import Datatable from "../components/datatable"
// Fetching data
require("es6-promise").polyfill();
require("isomorphic-fetch")
const IndexPage = () => {
const [data, setData] = useState([]);
const [q, setQ] = useState("");
const [totalRows, setTotalRows] = useState("Loading...");
const [displayedRows, setdisplayedRows] = useState("")
function updateTotalRows (num) {
setTotalRows(num)
}
function updateDisplayedRows (num) {
setdisplayedRows(num)
}
// transform JSON
function renameKey ( obj, oldKey, newKey ) {
obj[newKey] = obj[oldKey];
delete obj[oldKey];
}
function deleteKey (obj, key) {
delete obj[key]
}
useEffect(() => {
// Change when API in production
fetch("http://localhost:8080/api/tests")
.then((response) => response.json())
.then((json) => {
// set data in state
updateTotalRows(json.length)
updateDisplayedRows(json.length)
setData(json)
})
}, []);
function search(rows){
const columns = rows[0] && Object.keys(rows[0]);
let output = rows.filter(
(row) =>
columns.some(column => row[column].toString().toLowerCase().indexOf(q.toLowerCase()) > -1)
);
console.log(output.length); // works
updateDisplayedRows(output.length); // causes infinite loop error
return output
}
return (
<Layout>
<h1>Active Tests: {totalRows}</h1>
<p> Showing {displayedRows} of {totalRows} </p>
<input type="text" value={q} onChange={(e) => setQ(e.target.value)}/>
<Datatable data={search(data)} />
</Layout>
);
}
export default IndexPage
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment