import type { Project } from "../types/project";
import type { Table } from "../types/table";
import { useState } from "react";
export interface TablesState {
tables: Table[]
}
export interface TablesActions {
addTable: (table: Table) => void,
deleteTable: (id: string) => void,
updateTable: (updatedTable: Table) => void
}
export interface TableStateAndActions {
tableState: TablesState,
tableActions: TablesActions
}
export function useTables(project: Project): TableStateAndActions {
const [tables, setTables] = useState<Table[]>(project.tables);
const addTable = async (table: Table) => {
setTables(cur => [...cur, table])
// await fetch(`/api/projects/${project.id}/tables`, {
// method: "POST",
// headers: {
// 'Content-Type': 'application/json',
// },
// body: JSON.stringify({
// newTable: table,
// }),
// });
}
const deleteTable = async (id: string) => {
setTables(cur => cur.filter((cur) => cur.id !== id))
// await fetch(`/api/projects/${project.id}/tables/${id}`, {
// method: "DELETE",
// });
}
const updateTable = async (updatedTable: Table) => {
setTables(cur => cur.map((table) => table.id === updatedTable.id ? updatedTable : table));
// await fetch(`/api/projects/${project.id}/tables/${updatedTable.id}`, {
// method: "PUT",
// headers: {
// 'Content-Type': 'application/json',
// },
// body: JSON.stringify({
// table: updatedTable,
// }),
// });
}
return {
tableState: { tables },
tableActions: {
addTable,
updateTable,
deleteTable
}
}
}