/
index.tsx
117 lines (102 loc) · 2.42 KB
/
index.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
/** @module Components.Project.Simulation.Delete */
import { useCallback, useContext, useState } from 'react'
import { Typography } from 'antd'
import {
IFrontMutateProject,
IFrontProject,
IFrontSimulationsItem,
IFrontMutateSimulationsItem
} from '@/api/index.d'
import { NotificationContext } from '@/context/notification'
import { addError } from '@/context/notification/actions'
import { DeleteButton } from '@/components/assets/button'
import SimulationAPI from '@/api/simulation'
/**
* Props
*/
export type Project = Pick<IFrontProject, 'id' | 'simulations'>
export type Simulation = Pick<IFrontSimulationsItem, 'id' | 'name'>
export type Swr = {
mutateProject: (project: IFrontMutateProject) => Promise<void>
delOneSimulation: (simulation: IFrontMutateSimulationsItem) => Promise<void>
}
export interface IProps {
project: Project
simulation: Simulation
swr: Swr
}
/**
* Errors
*/
export const errors = {
del: 'Unable to delete simulation'
}
/**
* On delete
* @param project Project
* @param simulation Simulation
* @param swr SWR
*/
export const _onDelete = async (
project: Project,
simulation: Simulation,
swr: Swr
): Promise<void> => {
// API
await SimulationAPI.del(simulation)
// Mutate project
const filteredSimulations = project.simulations.filter(
(s: string) => s !== simulation.id
)
await swr.mutateProject({
id: project.id,
simulations: filteredSimulations
})
// Mutate simulations
await swr.delOneSimulation({ id: simulation.id })
}
/**
* Delete
* @param props Props
* @returns Delete
*/
const Delete: React.FunctionComponent<IProps> = ({
project,
simulation,
swr
}) => {
// State
const [loading, setLoading] = useState<boolean>(false)
// Context
const { dispatch } = useContext(NotificationContext)
/**
* On delete
*/
const onDelete = useCallback(async (): Promise<void> => {
setLoading(true)
try {
await _onDelete(project, simulation, swr)
} catch (err: any) {
dispatch(addError({ title: errors.del, err }))
throw err
} finally {
setLoading(false)
}
}, [project, simulation, swr, dispatch])
/**
* Render
*/
return (
<DeleteButton
loading={loading}
text={
<>
Are you sure you want to delete the simulation{' '}
<Typography.Text strong>{simulation.name}</Typography.Text>?
</>
}
onDelete={onDelete}
/>
)
}
export default Delete