File "use-ajax.js"

Full Path: /home/warrior1/public_html/languages/wp-content-20241001222009/plugins/elementor/app/assets/js/hooks/use-ajax.js
File size: 1.38 KB
MIME-type: text/x-java
Charset: utf-8

import { useState, useEffect } from 'react';

export default function useAjax() {
	const [ ajax, setAjax ] = useState( null ),
		initialStatusKey = 'initial',
		uploadInitialState = {
			status: initialStatusKey,
			isComplete: false,
			response: null,
		},
		[ ajaxState, setAjaxState ] = useState( uploadInitialState ),
		ajaxActions = {
			reset: () => setAjaxState( initialStatusKey ),
		};

	useEffect( () => {
		if ( ajax ) {
			const formData = new FormData();

			if ( ajax.data ) {
				for ( const key in ajax.data ) {
					formData.append( key, ajax.data[ key ] );
				}

				if ( ! ajax.data.nonce ) {
					formData.append( '_nonce', elementorCommon.config.ajax.nonce );
				}
			}

			const options = {
				type: 'post',
				url: elementorCommon.config.ajax.url,
				headers: {},
				cache: false,
				contentType: false,
				processData: false,
				...ajax,
				data: formData,
				success: ( response ) => {
					const status = response.success ? 'success' : 'error';

					setAjaxState( ( prevState ) => ( { ...prevState, status, response: response?.data } ) );
				},
				error: () => {
					setAjaxState( ( prevState ) => ( { ...prevState, status: 'error' } ) );
				},
				complete: () => {
					setAjaxState( ( prevState ) => ( { ...prevState, isComplete: true } ) );
				},
			};

			jQuery.ajax( options );
		}
	}, [ ajax ] );

	return {
		ajax,
		setAjax,
		ajaxState,
		ajaxActions,
	};
}