From cde4d5969215b02f51f0c2f42343ebb2db07b274 Mon Sep 17 00:00:00 2001 From: David Glymph Date: Thu, 3 Aug 2023 12:57:17 -0400 Subject: [PATCH] add AbortController and try/catch to fetch req --- api_routes/gpt.js | 2 ++ src/pages/answer/GPTForm.jsx | 38 +++++++++++++++++++++++++----------- 2 files changed, 29 insertions(+), 11 deletions(-) diff --git a/api_routes/gpt.js b/api_routes/gpt.js index 7c694bfa..c034d009 100644 --- a/api_routes/gpt.js +++ b/api_routes/gpt.js @@ -12,6 +12,8 @@ router.route('/auth') return; } + await new Promise((resolve) => setTimeout(resolve, 2000)); + res.send({ status: 'success', token: 'secretToken', diff --git a/src/pages/answer/GPTForm.jsx b/src/pages/answer/GPTForm.jsx index c17b5862..a0d8f186 100644 --- a/src/pages/answer/GPTForm.jsx +++ b/src/pages/answer/GPTForm.jsx @@ -1,4 +1,6 @@ -import React, { useContext, useState } from 'react'; +import React, { + useContext, useRef, useState, +} from 'react'; import { Button, Dialog, DialogActions, DialogContent, DialogContentText, DialogTitle, Link, TextField, @@ -12,6 +14,13 @@ const EnableForm = ({ open, handleClose }) => { const [error, setError] = useState(''); const [loading, setLoading] = useState(false); + const controllerRef = useRef(new AbortController()); + + const handleCloseWithAbort = () => { + if (controllerRef.current) { controllerRef.current.abort(); } + handleClose(); + }; + const onSubmit = async (e) => { e.preventDefault(); setError(''); @@ -23,13 +32,20 @@ const EnableForm = ({ open, handleClose }) => { setLoading(true); - const res = await fetch('/api/gpt/auth', { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - }, - body: JSON.stringify({ pw: password }), - }); + let res; + try { + res = await fetch('/api/gpt/auth', { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ pw: password }), + signal: controllerRef.current ? controllerRef.current.signal : undefined, + }); + } catch (err) { + setError('An error has occurred, please try again later'); + return; + } if (res.status !== 200) { setError(res.statusText); @@ -45,12 +61,12 @@ const EnableForm = ({ open, handleClose }) => { setPassword(''); setLoading(false); setToken(apiResponse.token); - handleClose(); + handleCloseWithAbort(); } }; return ( - +
Enable GPT Mode @@ -89,7 +105,7 @@ const EnableForm = ({ open, handleClose }) => { -