Skip to content

Instantly share code, notes, and snippets.

@johannschopplich
Last active February 12, 2024 13:19
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save johannschopplich/721f3ec6f9ee8095c40c50e9972541f5 to your computer and use it in GitHub Desktop.
Save johannschopplich/721f3ec6f9ee8095c40c50e9972541f5 to your computer and use it in GitHub Desktop.
Fetch data from Google Sheets API in TypeScript
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