Skip to content

Commit

Permalink
Merge pull request #166 from starboardcoop/issue/145
Browse files Browse the repository at this point in the history
Pull out things request logic
  • Loading branch information
mdantuono authored Jun 1, 2021
2 parents db05472 + 6838dbe commit 00ebb7a
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 20 deletions.
29 changes: 29 additions & 0 deletions src/routes/_api/things.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
async function getAll() {
let data;
let now = new Date();

let previousRefresh = new Date(localStorage.getItem("previousRefresh"));
if (Math.abs(now - previousRefresh) > 120000) {
data = _getAll();
localStorage.setItem("previousRefresh", now.toUTCString());
} else {
data = JSON.parse(localStorage.getItem("data"));

console.log('Previous data refreshed.');
}

return data;
}

async function _getAll() {
const result = await fetch(`/.netlify/functions/things`);
let data = await result.json();
localStorage.setItem("data", JSON.stringify(data));

console.log('Refreshed data from API.');
return data;
}

export default {
getAll
}
23 changes: 3 additions & 20 deletions src/routes/index.svelte
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
<script>
import { onMount } from "svelte";
import things from "./_api/things.js"
import Header from "../components/Header.svelte";
import Scroller from "../components/Scroller.svelte";
import TextInput from "../components/TextInput.svelte";
Expand All @@ -8,28 +9,10 @@
let searchResults = [];
let searchText = "";
onMount(() => {
let now = new Date();
let previousRefresh = new Date(localStorage.getItem("previousRefresh"));
if (Math.abs(now - previousRefresh) > 120000) {
thingify();
localStorage.setItem("previousRefresh", now.toUTCString());
} else {
data = JSON.parse(localStorage.getItem("data"));
console.log('Previous data refreshed.');
}
onMount(async () => {
data = await things.getAll();
});
async function thingify() {
const result = await fetch(`/.netlify/functions/things`);
data = await result.json();
localStorage.setItem("data", JSON.stringify(data));
console.log('Refreshed data from API.');
}
function filterThings(category) {
return data.things.filter(thing => thing.categories.includes(category));
}
Expand Down

0 comments on commit 00ebb7a

Please sign in to comment.