Last active
February 12, 2024 13:19
-
-
Save johannschopplich/721f3ec6f9ee8095c40c50e9972541f5 to your computer and use it in GitHub Desktop.
Fetch data from Google Sheets API in TypeScript
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
export interface SpreadsheetValues { | |
majorDimension: "DIMENSION_UNSPECIFIED" | "ROWS" | "COLUMNS"; | |
range: string; | |
values: string[][]; | |
} | |
export async function getSpreadsheetValues( | |
id: string, | |
sheet: string | |
): Promise<Record<string, string>[]> { | |
let data: SpreadsheetValues; | |
try { | |
const response = await fetch( | |
`https://sheets.googleapis.com/v4/spreadsheets/${id}/values/${sheet}?key=${ | |
import.meta.env.VITE_GOOGLE_API_KEY | |
}` | |
); | |
data = await response.json(); | |
} catch (e) { | |
console.error("Error fetching spreadsheet data:", e); | |
return []; | |
} | |
const rows: Record<string, string>[] = []; | |
const rawRows: string[][] = data.values || [[]]; | |
const headers: string[] = rawRows.shift() || []; | |
for (const row of rawRows) { | |
const rowData = row.reduce<Record<string, string>>((acc, cell, index) => { | |
acc[headers[index]] = cell; | |
return acc; | |
}, {}); | |
rows.push(rowData); | |
} | |
return rows; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment