1
1
import debounce from 'lodash/debounce' ;
2
2
import { SetterOrUpdater , useRecoilValue } from 'recoil' ;
3
- import { useState , useEffect , useMemo , useCallback } from 'react' ;
3
+ import { useState , useEffect , useMemo , useCallback , useRef } from 'react' ;
4
4
import { LocalStorageKeys , TFile } from 'librechat-data-provider' ;
5
5
import type { ExtendedFile } from '~/common' ;
6
6
import { useChatFormContext } from '~/Providers' ;
@@ -52,7 +52,7 @@ export const useAutoSave = ({
52
52
}
53
53
} ;
54
54
55
- const restoreFiles = useCallback (
55
+ const restoreFilesRaw = useCallback (
56
56
( id : string ) => {
57
57
const filesDraft = JSON . parse (
58
58
( localStorage . getItem ( `${ LocalStorageKeys . FILES_DRAFT } ${ id } ` ) ?? '' ) || '[]' ,
@@ -92,14 +92,40 @@ export const useAutoSave = ({
92
92
[ fileList , setFiles ] ,
93
93
) ;
94
94
95
- const restoreText = useCallback (
95
+ const restoreTextRaw = useCallback (
96
96
( id : string ) => {
97
97
const savedDraft = ( localStorage . getItem ( `${ LocalStorageKeys . TEXT_DRAFT } ${ id } ` ) ?? '' ) || '' ;
98
98
setValue ( 'text' , decodeBase64 ( savedDraft ) ) ;
99
99
} ,
100
100
[ setValue ] ,
101
101
) ;
102
102
103
+ const restoreFilesRef = useRef (
104
+ debounce ( ( id : string ) => {
105
+ restoreFilesRaw ( id ) ;
106
+ } , 500 ) ,
107
+ ) ;
108
+
109
+ const restoreTextRef = useRef (
110
+ debounce ( ( id : string ) => {
111
+ restoreTextRaw ( id ) ;
112
+ } , 500 ) ,
113
+ ) ;
114
+
115
+ const restoreFiles = useCallback (
116
+ ( id : string ) => {
117
+ restoreFilesRef . current ( id ) ;
118
+ } ,
119
+ [ restoreFilesRef ] ,
120
+ ) ;
121
+
122
+ const restoreText = useCallback (
123
+ ( id : string ) => {
124
+ restoreTextRef . current ( id ) ;
125
+ } ,
126
+ [ restoreTextRef ] ,
127
+ ) ;
128
+
103
129
const saveText = useCallback (
104
130
( id : string ) => {
105
131
if ( ! textAreaRef ?. current ) {
@@ -150,6 +176,16 @@ export const useAutoSave = ({
150
176
} ;
151
177
} , [ conversationId , saveDrafts , textAreaRef ] ) ;
152
178
179
+ // Clean up debounced functions on unmount
180
+ useEffect ( ( ) => {
181
+ const filesRefCurrent = restoreFilesRef . current ;
182
+ const textRefCurrent = restoreTextRef . current ;
183
+ return ( ) => {
184
+ filesRefCurrent . cancel ( ) ;
185
+ textRefCurrent . cancel ( ) ;
186
+ } ;
187
+ } , [ ] ) ;
188
+
153
189
useEffect ( ( ) => {
154
190
// This useEffect is responsible for saving the current conversation's draft and
155
191
// restoring the new conversation's draft when switching between conversations.
@@ -171,6 +207,7 @@ export const useAutoSave = ({
171
207
saveText ( currentConversationId ) ;
172
208
}
173
209
210
+ // Call the debounced restore functions
174
211
restoreText ( conversationId ) ;
175
212
restoreFiles ( conversationId ) ;
176
213
} catch ( e ) {
0 commit comments