Last active
December 26, 2021 09:57
-
-
Save MrSunshyne/868044855b08b40f358e14fd2ae12f35 to your computer and use it in GitHub Desktop.
A Vue3 Composable to get Google Sheet Data.
This file contains hidden or 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
/* | |
//INPUT | |
API_KEY | |
SHEET_ID | |
SHEET_NAME(optional) | |
// Returns | |
headers | |
items(formatter as { header: value } | |
loading ref | |
*/ | |
import { ref, reactive, Ref } from "vue" | |
interface I { | |
[key: string]: any | |
} | |
export default (API_KEY: string = 'xxx', SHEET_ID: string = 'yyy', SHEET_NAME: string = 'Sheet1') => { | |
const loading: Ref<boolean> = ref(true) | |
let headers: string[] = reactive([]) | |
let items = reactive([]) as I[] | |
function formatter(input: string[]) { | |
const entry = input | |
let records = entry.splice(1, entry.length) | |
let columns = entry[0].length | |
for (let i = 0; i < columns; i++) { | |
headers.push(entry[0][i]) | |
} | |
for (let i = 0; i < records.length; i++) { | |
const item = {} as I | |
for (let j = 0; j < headers.length; j++) { | |
item[headers[j]] = records[i][j] | |
} | |
items.push(item) | |
} | |
} | |
fetch(`https://sheets.googleapis.com/v4/spreadsheets/${SHEET_ID}/values/${SHEET_NAME}?key=${API_KEY}`) | |
.then(res => res.json()) | |
.then(res => { | |
loading.value = false | |
formatter(res.values) | |
}).catch(err => { | |
console.log(err) | |
}) | |
return { | |
headers: readonly(headers), | |
items: readonly(items), | |
loading | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment