@@ -2,14 +2,25 @@ import { Avatar, CardHeader, Switch, Tooltip, Typography } from '@mui/material';
2
2
3
3
import { CatalogItemRichened } from '../../types/catalog' ;
4
4
import { formatName } from '../../formatName' ;
5
- import { format } from 'path ' ;
5
+ import { useEffect , useState } from 'react ' ;
6
6
7
7
type TopProps = {
8
8
onToggleRegister : ( checked : boolean ) => void ;
9
9
item : CatalogItemRichened ;
10
10
} ;
11
11
12
12
export default function Top ( { item, onToggleRegister } : TopProps ) {
13
+ // For some unknown reason, item.registered is not updated right away when the user toggles the switch.
14
+ // This `toggled` state is used to control the switch in the UI. Its main purpose is to do optimistic UI updates.
15
+ // When the user toggles the switch. The `useEffect` hook is used to synchronize the `toggled` state with the `item.registered`
16
+ // prop, which is the source of truth for the registration status of the item. This way, if the `item.registered` prop changes
17
+ // (e.g., due to a successful registration or unregistration), the switch will reflect the correct state.
18
+ const [ toggled , setToggled ] = useState ( item . registered ) ;
19
+
20
+ useEffect ( ( ) => {
21
+ setToggled ( item . registered ) ;
22
+ } , [ item . registered ] ) ;
23
+
13
24
return (
14
25
< CardHeader
15
26
sx = { { padding : 0 } }
@@ -45,10 +56,12 @@ export default function Top({ item, onToggleRegister }: TopProps) {
45
56
}
46
57
>
47
58
< Switch
48
- checked = { item . registered }
59
+ checked = { toggled }
49
60
onChange = { ( event , checked ) => {
50
61
event . stopPropagation ( ) ;
51
62
event . preventDefault ( ) ;
63
+
64
+ setToggled ( checked ) ;
52
65
onToggleRegister ( checked ) ;
53
66
} }
54
67
/>
0 commit comments