fix: submit completion by fetch

This commit is contained in:
jialin
2024-06-24 19:14:42 +08:00
parent 4dcd11e119
commit bd6b3dcbe3
5 changed files with 164 additions and 39 deletions
+61
View File
@@ -0,0 +1,61 @@
import qs from 'query-string';
import { useRef } from 'react';
export const createEventSourceURL = (url: string) => {
const { host, protocol } = window.location;
return `${protocol}://${host}${url}`;
};
/*
0: connecting
1: connect successfully
2: closed
*/
export default function useEventSource() {
const eventSourceRef = useRef<any>(null);
const createEventSourceConnection = (query: {
url: string;
params: any;
onmessage?: (data: any) => void;
}) => {
eventSourceRef.current?.close?.();
const { url, params, onmessage = () => {} } = query;
const sseurl = createEventSourceURL(url);
eventSourceRef.current = new EventSource(
`${url}?${qs.stringify({
...params
})}`,
{
withCredentials: true
}
);
eventSourceRef.current.onmessage = (res: any) => {
try {
const data = JSON.parse(res.data);
console.log('event source message: ', { data, resData: res });
onmessage(data);
} catch (error) {
// error
}
};
eventSourceRef.current.onopen = () => {
console.log('event source connected...');
};
eventSourceRef.current.onerror = (error: any) => {
console.log('event source error: ', error);
};
};
return {
eventSourceRef: eventSourceRef,
createEventSourceConnection
};
}