feat: add useEstimateController
This commit is contained in:
parent
da26628f69
commit
f8f769fd49
60
src/hooks/floorPlan/estimate/useEstimateController.js
Normal file
60
src/hooks/floorPlan/estimate/useEstimateController.js
Normal file
@ -0,0 +1,60 @@
|
||||
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,
|
||||
}
|
||||
}
|
||||
Loading…
x
Reference in New Issue
Block a user