Skip to content

Commit

Permalink
feat: add per session caching
Browse files Browse the repository at this point in the history
  • Loading branch information
cdransf committed Feb 29, 2024
1 parent 8d50cf9 commit 0d12290
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 12 deletions.
27 changes: 16 additions & 11 deletions api-text.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,26 +18,31 @@ class ApiText extends HTMLElement {

async connectedCallback() {
if (this.shadowRoot) return;
const data = { ...(await this.data) };
let shadowroot = this.attachShadow({ mode: 'open' })
let slot = document.createElement('slot')
shadowroot.appendChild(slot)

const data = { ...(await this.data) };
const loading = this.querySelector('.loading')
const content = this.querySelector('.content')
const value = data['content']

if (!value) {
loading.style.display = 'none'
content.style.display = 'none'
const cacheKey = this.url || 'api-text-cache'
const cache = sessionStorage?.getItem(cacheKey) || loading.innerHTML
const loadText = (string) => {
if (string && content.style.opacity !== '1') {
loading.style.opacity = '0'
loading.style.display = 'none'
content.style.opacity = '1'
content.innerHTML = value
} else if (string && content.style.opacity === '1') {
content.innerHTML = value
}
}

if (value) {
loading.style.opacity = '0'
loading.style.display = 'none'
content.style.opacity = '1'
content.innerHTML = value
}
loadText(cache);
loadText(value);

sessionStorage?.setItem(cacheKey, JSON.stringify(value))
}

get data() {
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@cdransf/api-text",
"version": "1.0.0",
"version": "1.1.0",
"description": "A web component to load text from an API and display it.",
"main": "api-text.js",
"repository": {
Expand Down

0 comments on commit 0d12290

Please sign in to comment.