Skip to content

Commit

Permalink
add AbortController and try/catch to fetch req
Browse files Browse the repository at this point in the history
  • Loading branch information
Woozl committed Aug 3, 2023
1 parent 4e65e3f commit cde4d59
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 11 deletions.
2 changes: 2 additions & 0 deletions api_routes/gpt.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ router.route('/auth')
return;
}

await new Promise((resolve) => setTimeout(resolve, 2000));

res.send({
status: 'success',
token: 'secretToken',
Expand Down
38 changes: 27 additions & 11 deletions src/pages/answer/GPTForm.jsx
Original file line number Diff line number Diff line change
@@ -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,
Expand All @@ -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('');
Expand All @@ -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);
Expand All @@ -45,12 +61,12 @@ const EnableForm = ({ open, handleClose }) => {
setPassword('');
setLoading(false);
setToken(apiResponse.token);
handleClose();
handleCloseWithAbort();
}
};

return (
<Dialog open={open} onClose={handleClose} aria-labelledby="gpt-dialog-title">
<Dialog open={open} onClose={handleCloseWithAbort} aria-labelledby="gpt-dialog-title">
<form onSubmit={onSubmit}>
<DialogTitle id="gpt-dialog-title">Enable GPT Mode</DialogTitle>
<DialogContent>
Expand Down Expand Up @@ -89,7 +105,7 @@ const EnableForm = ({ open, handleClose }) => {

</DialogContent>
<DialogActions>
<Button onClick={handleClose} color="default">
<Button onClick={handleCloseWithAbort} color="default">
Cancel
</Button>
<Button
Expand Down

0 comments on commit cde4d59

Please sign in to comment.