import { useState } from 'react' ; import { Options } from 'dahlia-request' ; import { fetch } from './fetch' ; import { Update , UpdateResult } from './types' ; function getOptions ( options ? ) { const defaultOpt = { method : 'POST' } as Options ; if ( ! options ) return defaultOpt ; return { ... defaultOpt , ... options } ; } export const useUpdate = < T = any > ( url , options ? ) => { const initialState = { } as UpdateResult < T > ; const [ result , setState ] = useState ( initialState ) ; const updateData = async ( updateOptions ? ) => { setState ( prev => ( { ... prev , loading : true } ) ) ; try { let opt = getOptions ( options ) ; if ( updateOptions ) opt = { ... opt , ... updateOptions } ; const data = await fetch ( url , opt ) ; setState ( prev => ( { ... prev , loading : false , data } ) ) ; } catch ( error ) { setState ( prev => ( { ... prev , loading : false , error } ) ) ; } } ; const update = ( updateOptions ? ) : any => { updateData ( updateOptions ) ; } ; const out = [ update , result ] ; return out ; } ;