File tree Expand file tree Collapse file tree 1 file changed +26
-13
lines changed Expand file tree Collapse file tree 1 file changed +26
-13
lines changed Original file line number Diff line number Diff line change 1- import { AnyDocumentId , Repo } from "@automerge/automerge-repo" ;
1+ import { AnyDocumentId , DocHandle , Repo } from "@automerge/automerge-repo" ;
22import {
33 RepoContext ,
44 useDocument ,
@@ -9,6 +9,7 @@ import fastDeepEqual from "fast-deep-equal";
99import {
1010 createContext ,
1111 ReactNode ,
12+ useCallback ,
1213 useContext ,
1314 useRef ,
1415 useSyncExternalStore ,
@@ -163,21 +164,33 @@ export function createFunctions<
163164
164165 function useDeleteEntity ( ) {
165166 const id = useSpaceId ( ) ;
166- const [ , changeDoc ] = useDocument < DocumentContent > ( id as AnyDocumentId ) ;
167167
168- function deleteEntity ( entityId : string ) {
169- let result = false ;
170- changeDoc ( ( doc ) => {
171- if ( doc . entities ) {
172- if ( doc . entities [ entityId ] ) {
173- delete doc . entities [ entityId ] ;
174- result = true ;
175- }
176- }
177- } ) ;
178- return result ;
168+ // can't use useDocument here because it would trigger a re-render every time the document changes
169+ const repo = useRepo ( ) ;
170+ const handle = id ? repo . find < DocumentContent > ( id as AnyDocumentId ) : null ;
171+ const handleRef = useRef < DocHandle < DocumentContent > | null > ( handle ) ;
172+ if ( handle !== handleRef . current ) {
173+ handleRef . current = handle ;
179174 }
180175
176+ const deleteEntity = useCallback (
177+ function deleteEntity ( entityId : string ) {
178+ let result = false ;
179+ if ( ! handle ) return result ;
180+ handle . change ( ( doc ) => {
181+ if ( doc . entities ) {
182+ if ( doc . entities [ entityId ] ) {
183+ delete doc . entities [ entityId ] ;
184+ result = true ;
185+ }
186+ }
187+ } ) ;
188+
189+ return result ;
190+ } ,
191+ [ id ]
192+ ) ;
193+
181194 return deleteEntity ;
182195 }
183196
You can’t perform that action at this time.
0 commit comments