| 1 |
import { useState, useEffect } from 'react'; |
| 2 |
|
| 3 |
export default function useAjax() { |
| 4 |
const [ ajax, setAjax ] = useState( null ), |
| 5 |
initialStatusKey = 'initial', |
| 6 |
uploadInitialState = { |
| 7 |
status: initialStatusKey, |
| 8 |
isComplete: false, |
| 9 |
response: null, |
| 10 |
}, |
| 11 |
[ ajaxState, setAjaxState ] = useState( uploadInitialState ), |
| 12 |
ajaxActions = { |
| 13 |
reset: () => setAjaxState( initialStatusKey ), |
| 14 |
}; |
| 15 |
|
| 16 |
useEffect( () => { |
| 17 |
if ( ajax ) { |
| 18 |
const formData = new FormData(); |
| 19 |
|
| 20 |
if ( ajax.data ) { |
| 21 |
for ( const key in ajax.data ) { |
| 22 |
formData.append( key, ajax.data[ key ] ); |
| 23 |
} |
| 24 |
|
| 25 |
if ( ! ajax.data.nonce ) { |
| 26 |
formData.append( '_nonce', elementorCommon.config.ajax.nonce ); |
| 27 |
} |
| 28 |
} |
| 29 |
|
| 30 |
const options = { |
| 31 |
type: 'post', |
| 32 |
url: elementorCommon.config.ajax.url, |
| 33 |
headers: {}, |
| 34 |
cache: false, |
| 35 |
contentType: false, |
| 36 |
processData: false, |
| 37 |
...ajax, |
| 38 |
data: formData, |
| 39 |
success: ( response ) => { |
| 40 |
const status = response.success ? 'success' : 'error'; |
| 41 |
|
| 42 |
setAjaxState( ( prevState ) => ( { ...prevState, status, response: response?.data } ) ); |
| 43 |
}, |
| 44 |
error: () => { |
| 45 |
setAjaxState( ( prevState ) => ( { ...prevState, status: 'error' } ) ); |
| 46 |
}, |
| 47 |
complete: () => { |
| 48 |
setAjaxState( ( prevState ) => ( { ...prevState, isComplete: true } ) ); |
| 49 |
}, |
| 50 |
}; |
| 51 |
|
| 52 |
jQuery.ajax( options ); |
| 53 |
} |
| 54 |
}, [ ajax ] ); |
| 55 |
|
| 56 |
return { |
| 57 |
ajax, |
| 58 |
setAjax, |
| 59 |
ajaxState, |
| 60 |
ajaxActions, |
| 61 |
}; |
| 62 |
} |
| 63 |
|