61 lines
1.4 KiB
JavaScript
61 lines
1.4 KiB
JavaScript
import { useAxios } from '@/hooks/useAxios'
|
|
import { useReducer } from 'react'
|
|
|
|
const reducer = (prevState, nextState) => {
|
|
return { ...prevState, ...nextState }
|
|
}
|
|
|
|
// Constants
|
|
const ESTIMATE_API_ENDPOINT = '/api/estimates' // API 엔드포인트 정의
|
|
|
|
const defaultEstimateData = {
|
|
name: '',
|
|
objectName: '',
|
|
estimateDate: '',
|
|
itemList: [{ id: 1, name: '' }],
|
|
}
|
|
|
|
// Helper functions
|
|
const updateItemInList = (itemList, id, updates) => {
|
|
return itemList.map((item) => (item.id === id ? { ...item, ...updates } : item))
|
|
}
|
|
|
|
export const useEstimateController = () => {
|
|
const { promisePost } = useAxios()
|
|
const [state, setState] = useReducer(reducer, defaultEstimateData)
|
|
|
|
const updateItem = (id, updates) => {
|
|
setState({
|
|
itemList: updateItemInList(state.itemList, id, updates),
|
|
})
|
|
}
|
|
|
|
const addItem = () => {
|
|
const newId = Math.max(...state.itemList.map((item) => item.id)) + 1
|
|
setState({
|
|
itemList: [...state.itemList, { id: newId, name: '' }],
|
|
})
|
|
}
|
|
|
|
const handleEstimateSubmit = async () => {
|
|
try {
|
|
const result = await promisePost({
|
|
url: ESTIMATE_API_ENDPOINT,
|
|
data: state,
|
|
})
|
|
return result
|
|
} catch (error) {
|
|
console.error('Failed to submit estimate:', error)
|
|
throw error
|
|
}
|
|
}
|
|
|
|
return {
|
|
state,
|
|
setState,
|
|
updateItem,
|
|
addItem,
|
|
handleEstimateSubmit,
|
|
}
|
|
}
|