11'use client'
22
3- import { useEffect , useState } from 'react'
3+ import { useState } from 'react'
44import { createLogger } from '@sim/logger'
55import { AlertCircle } from 'lucide-react'
66import { useParams } from 'next/navigation'
@@ -17,6 +17,12 @@ import {
1717 Textarea ,
1818} from '@/components/emcn'
1919import type { ColumnDefinition , TableInfo , TableRow } from '@/lib/table'
20+ import {
21+ useCreateTableRow ,
22+ useDeleteTableRow ,
23+ useDeleteTableRows ,
24+ useUpdateTableRow ,
25+ } from '@/hooks/queries/tables'
2026
2127const logger = createLogger ( 'RowModal' )
2228
@@ -92,126 +98,78 @@ function formatValueForInput(value: unknown, type: string): string {
9298 return String ( value )
9399}
94100
101+ function getInitialRowData (
102+ mode : RowModalProps [ 'mode' ] ,
103+ columns : ColumnDefinition [ ] ,
104+ row ?: TableRow
105+ ) : Record < string , unknown > {
106+ if ( mode === 'add' && columns . length > 0 ) {
107+ return createInitialRowData ( columns )
108+ }
109+ if ( mode === 'edit' && row ) {
110+ return row . data
111+ }
112+ return { }
113+ }
114+
95115export function RowModal ( { mode, isOpen, onClose, table, row, rowIds, onSuccess } : RowModalProps ) {
96116 const params = useParams ( )
97117 const workspaceId = params . workspaceId as string
118+ const tableId = table . id
98119
99120 const schema = table ?. schema
100121 const columns = schema ?. columns || [ ]
101122
102- const [ rowData , setRowData ] = useState < Record < string , unknown > > ( { } )
123+ const [ rowData , setRowData ] = useState < Record < string , unknown > > ( ( ) =>
124+ getInitialRowData ( mode , columns , row )
125+ )
103126 const [ error , setError ] = useState < string | null > ( null )
104- const [ isSubmitting , setIsSubmitting ] = useState ( false )
105-
106- // Initialize form data based on mode
107- useEffect ( ( ) => {
108- if ( ! isOpen ) return
109-
110- if ( mode === 'add' && columns . length > 0 ) {
111- setRowData ( createInitialRowData ( columns ) )
112- } else if ( mode === 'edit' && row ) {
113- setRowData ( row . data )
114- }
115- } , [ isOpen , mode , columns , row ] )
127+ const createRowMutation = useCreateTableRow ( { workspaceId, tableId } )
128+ const updateRowMutation = useUpdateTableRow ( { workspaceId, tableId } )
129+ const deleteRowMutation = useDeleteTableRow ( { workspaceId, tableId } )
130+ const deleteRowsMutation = useDeleteTableRows ( { workspaceId, tableId } )
131+ const isSubmitting =
132+ createRowMutation . isPending ||
133+ updateRowMutation . isPending ||
134+ deleteRowMutation . isPending ||
135+ deleteRowsMutation . isPending
116136
117137 const handleFormSubmit = async ( e : React . FormEvent ) => {
118138 e . preventDefault ( )
119139 setError ( null )
120- setIsSubmitting ( true )
121140
122141 try {
123142 const cleanData = cleanRowData ( columns , rowData )
124143
125144 if ( mode === 'add' ) {
126- const res = await fetch ( `/api/table/${ table ?. id } /rows` , {
127- method : 'POST' ,
128- headers : { 'Content-Type' : 'application/json' } ,
129- body : JSON . stringify ( { workspaceId, data : cleanData } ) ,
130- } )
131-
132- const result : { error ?: string } = await res . json ( )
133- if ( ! res . ok ) {
134- throw new Error ( result . error || 'Failed to add row' )
135- }
145+ await createRowMutation . mutateAsync ( cleanData )
136146 } else if ( mode === 'edit' && row ) {
137- const res = await fetch ( `/api/table/${ table ?. id } /rows/${ row . id } ` , {
138- method : 'PATCH' ,
139- headers : { 'Content-Type' : 'application/json' } ,
140- body : JSON . stringify ( { workspaceId, data : cleanData } ) ,
141- } )
142-
143- const result : { error ?: string } = await res . json ( )
144- if ( ! res . ok ) {
145- throw new Error ( result . error || 'Failed to update row' )
146- }
147+ await updateRowMutation . mutateAsync ( { rowId : row . id , data : cleanData } )
147148 }
148149
149150 onSuccess ( )
150151 } catch ( err ) {
151152 logger . error ( `Failed to ${ mode } row:` , err )
152153 setError ( err instanceof Error ? err . message : `Failed to ${ mode } row` )
153- } finally {
154- setIsSubmitting ( false )
155154 }
156155 }
157156
158157 const handleDelete = async ( ) => {
159158 setError ( null )
160- setIsSubmitting ( true )
161159
162160 const idsToDelete = rowIds ?? ( row ? [ row . id ] : [ ] )
163161
164162 try {
165163 if ( idsToDelete . length === 1 ) {
166- const res = await fetch ( `/api/table/${ table ?. id } /rows/${ idsToDelete [ 0 ] } ` , {
167- method : 'DELETE' ,
168- headers : { 'Content-Type' : 'application/json' } ,
169- body : JSON . stringify ( { workspaceId } ) ,
170- } )
171-
172- if ( ! res . ok ) {
173- const result : { error ?: string } = await res . json ( )
174- throw new Error ( result . error || 'Failed to delete row' )
175- }
164+ await deleteRowMutation . mutateAsync ( idsToDelete [ 0 ] )
176165 } else {
177- const results = await Promise . allSettled (
178- idsToDelete . map ( async ( rowId ) => {
179- const res = await fetch ( `/api/table/${ table ?. id } /rows/${ rowId } ` , {
180- method : 'DELETE' ,
181- headers : { 'Content-Type' : 'application/json' } ,
182- body : JSON . stringify ( { workspaceId } ) ,
183- } )
184-
185- if ( ! res . ok ) {
186- const result : { error ?: string } = await res . json ( ) . catch ( ( ) => ( { } ) )
187- throw new Error ( result . error || `Failed to delete row ${ rowId } ` )
188- }
189-
190- return rowId
191- } )
192- )
193-
194- const failures = results . filter ( ( r ) => r . status === 'rejected' )
195-
196- if ( failures . length > 0 ) {
197- const failureCount = failures . length
198- const totalCount = idsToDelete . length
199- const successCount = totalCount - failureCount
200- const firstError =
201- failures [ 0 ] . status === 'rejected' ? failures [ 0 ] . reason ?. message || 'Unknown error' : ''
202-
203- throw new Error (
204- `Failed to delete ${ failureCount } of ${ totalCount } row(s)${ successCount > 0 ? ` (${ successCount } deleted successfully)` : '' } . ${ firstError } `
205- )
206- }
166+ await deleteRowsMutation . mutateAsync ( idsToDelete )
207167 }
208168
209169 onSuccess ( )
210170 } catch ( err ) {
211171 logger . error ( 'Failed to delete row(s):' , err )
212172 setError ( err instanceof Error ? err . message : 'Failed to delete row(s)' )
213- } finally {
214- setIsSubmitting ( false )
215173 }
216174 }
217175
0 commit comments