|
1 | | -import { useState } from 'react'; |
| 1 | +import { useEffect, useRef, useState } from 'react'; |
2 | 2 | import axios from 'axios'; |
3 | 3 |
|
4 | 4 | export const useWebhookSubmit = () => { |
5 | 5 | const [isSubmitting, setIsSubmitting] = useState(false); |
6 | 6 | const [error, setError] = useState(null); |
| 7 | + const isMountedRef = useRef(true); |
| 8 | + const requestControllerRef = useRef(null); |
| 9 | + |
| 10 | + useEffect(() => { |
| 11 | + return () => { |
| 12 | + isMountedRef.current = false; |
| 13 | + if (requestControllerRef.current) { |
| 14 | + requestControllerRef.current.abort(); |
| 15 | + } |
| 16 | + }; |
| 17 | + }, []); |
7 | 18 |
|
8 | 19 | const submitForm = async (payload) => { |
9 | | - setIsSubmitting(true); |
10 | | - setError(null); |
| 20 | + const controller = new AbortController(); |
| 21 | + requestControllerRef.current = controller; |
| 22 | + |
| 23 | + if (isMountedRef.current) { |
| 24 | + setIsSubmitting(true); |
| 25 | + setError(null); |
| 26 | + } |
| 27 | + |
11 | 28 | try { |
12 | | - const response = await axios.post("https://hook.us1.make.com/nficb3d7swqkclkl467st4hp4cg65u8o", payload); |
| 29 | + const response = await axios.post( |
| 30 | + "https://hook.us1.make.com/nficb3d7swqkclkl467st4hp4cg65u8o", |
| 31 | + payload, |
| 32 | + { signal: controller.signal }, |
| 33 | + ); |
13 | 34 | return { success: true, data: response.data }; |
14 | 35 | } catch (err) { |
| 36 | + const isAborted = controller.signal.aborted || err?.name === "CanceledError"; |
| 37 | + if (isAborted) { |
| 38 | + return { success: false, error: null, errorMessage: "Request was cancelled." }; |
| 39 | + } |
| 40 | + |
15 | 41 | const errorMessage = (err && err.message) || 'An error occurred during submission.'; |
16 | 42 | const errorObject = err instanceof Error ? err : new Error(errorMessage); |
17 | | - setError(errorObject); |
| 43 | + if (isMountedRef.current) { |
| 44 | + setError(errorObject); |
| 45 | + } |
18 | 46 | return { success: false, error: errorObject, errorMessage }; |
19 | 47 | } finally { |
20 | | - setIsSubmitting(false); |
| 48 | + if (requestControllerRef.current === controller) { |
| 49 | + requestControllerRef.current = null; |
| 50 | + } |
| 51 | + if (isMountedRef.current) { |
| 52 | + setIsSubmitting(false); |
| 53 | + } |
21 | 54 | } |
22 | 55 | }; |
23 | 56 |
|
|
0 commit comments