Last active
October 17, 2024 20:55
-
-
Save nafeu/dff1ff0e9320b3207d8ffd9d0e91b33b to your computer and use it in GitHub Desktop.
Simple Template for JSONBIN in HTML Page
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const JSONBIN_BIN_ID = '...'; | |
const JSONBIN_URL = `https://api.jsonbin.io/v3/b/${JSONBIN_BIN_ID}`; | |
const JSONBIN_MASTER_KEY = '...'; | |
const JSONBIN_ACCESS_KEY = '...'; | |
function fetchData({ onSuccess, onFail }) { | |
const url = JSONBIN_URL; | |
const headers = new Headers(); | |
headers.append('X-Master-Key', JSONBIN_MASTER_KEY); | |
headers.append('X-Access-Key', JSONBIN_ACCESS_KEY); | |
const options = { | |
method: 'GET', | |
headers: headers, | |
}; | |
fetch(url, options) | |
.then(response => { | |
if (!response.ok) { | |
throw new Error(`HTTP error! Status: ${response.status}`); | |
} | |
return response.json(); | |
}) | |
.then(data => { | |
const myBinIsEmpty = data.record.data === [] || data.record.data.length === 0; | |
if (myBinIsEmpty) { | |
saveData(); | |
} else { | |
/* When you first load your app, and you get the existing data from the server */ | |
} | |
onSuccess(); | |
}) | |
.catch(error => { | |
console.error('Fetch error:', error); | |
onFail(); | |
}); | |
} | |
function saveData() { | |
const url = JSONBIN_URL; | |
const headers = new Headers(); | |
headers.append('X-Master-Key', JSONBIN_MASTER_KEY); | |
headers.append('X-Access-Key', JSONBIN_ACCESS_KEY); | |
headers.append('Content-Type', 'application/json'); | |
const postData = { | |
/* your post data */ | |
}; | |
const options = { | |
method: 'PUT', | |
headers: headers, | |
body: JSON.stringify(postData) | |
}; | |
fetch(url, options) | |
.then(response => { | |
if (!response.ok) { | |
throw new Error(`HTTP error! Status: ${response.status}`); | |
} | |
return response.json(); | |
}) | |
.then(data => { | |
/* do what you wanna do after saving */ | |
}) | |
.catch(error => { | |
console.error('Fetch error:', error); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment