@@ -104,6 +104,30 @@ async function deleteNoteRequest(id: string, getToken: GetToken): Promise<void>
104104 }
105105}
106106
107+ async function importNotes ( file : File , getToken : GetToken ) : Promise < void > {
108+ const url = BASEURL + "/notes/imports" ;
109+ const formData = new FormData ( ) ;
110+ formData . append ( "file" , file ) ;
111+
112+ const headers = await authHeaders ( getToken ) ;
113+
114+ try {
115+ const response = await fetch ( url , {
116+ method : "POST" ,
117+ headers,
118+ credentials : "include" ,
119+ body : formData ,
120+ } ) ;
121+
122+ if ( ! response . ok ) {
123+ throw new Error ( "request failed" ) ;
124+ }
125+ } catch ( err ) {
126+ console . error ( err ) ;
127+ throw err ;
128+ }
129+ }
130+
107131export function useNotes ( ) {
108132 const { isLoaded, isSignedIn, getToken } = useAuth ( ) ;
109133 const [ notes , setNotes ] = useState < Note [ ] > ( [ ] ) ;
@@ -211,6 +235,21 @@ export function useNotes() {
211235 [ getToken , notes ]
212236 ) ;
213237
238+ const handleImportNotes = useCallback (
239+ async ( file : File ) => {
240+ try {
241+ await importNotes ( file , getToken ) ;
242+
243+ const loadedNotes = await loadNotes ( getToken ) ;
244+ setNotes ( loadedNotes ) ;
245+ setActiveIndex ( Math . max ( loadedNotes . length - 1 , 0 ) ) ;
246+ } catch ( err ) {
247+ console . error ( err ) ;
248+ }
249+ } ,
250+ [ getToken ]
251+ ) ;
252+
214253 const activeNote = notes [ activeIndex ] ?? null ;
215254
216255 return {
@@ -219,6 +258,7 @@ export function useNotes() {
219258 activeNote,
220259 setActiveIndex,
221260 createNote,
261+ handleImportNotes,
222262 updateNoteContent,
223263 renameNote,
224264 deleteNote,
0 commit comments