mirror of
https://github.com/DeNNiiInc/dbgate.git
synced 2026-04-20 17:06:01 +00:00
socket.io integration, reload connection list after change
This commit is contained in:
18
web/src/utility/SocketProvider.js
Normal file
18
web/src/utility/SocketProvider.js
Normal file
@@ -0,0 +1,18 @@
|
||||
import io from 'socket.io-client';
|
||||
import React from 'react';
|
||||
|
||||
const SocketContext = React.createContext();
|
||||
|
||||
export function SocketProvider({ children }) {
|
||||
const [socket, setSocket] = React.useState();
|
||||
React.useEffect(() => {
|
||||
// const newSocket = io('http://localhost:3000', { transports: ['websocket'] });
|
||||
const newSocket = io('http://localhost:3000');
|
||||
setSocket(newSocket);
|
||||
}, []);
|
||||
return <SocketContext.Provider value={socket}>{children}</SocketContext.Provider>;
|
||||
}
|
||||
|
||||
export default function useSocket() {
|
||||
return React.useContext(SocketContext);
|
||||
}
|
||||
@@ -1,16 +1,33 @@
|
||||
import React from 'react';
|
||||
import axios from './axios';
|
||||
import useSocket from './SocketProvider';
|
||||
|
||||
export default function useFetch(url, defValue) {
|
||||
const [value, setValue] = React.useState(defValue);
|
||||
export default function useFetch({ defaultValue, reloadTrigger, url, ...config }) {
|
||||
const [value, setValue] = React.useState(defaultValue);
|
||||
const [loadCounter, setLoadCounter] = React.useState(0);
|
||||
const socket = useSocket();
|
||||
|
||||
const handleReload = () => {
|
||||
setLoadCounter(loadCounter + 1);
|
||||
};
|
||||
|
||||
async function loadValue() {
|
||||
const resp = await axios.get(url);
|
||||
const resp = await axios.request({
|
||||
method: 'get',
|
||||
url,
|
||||
...config,
|
||||
});
|
||||
setValue(resp.data);
|
||||
}
|
||||
React.useEffect(() => {
|
||||
loadValue();
|
||||
}, [url]);
|
||||
if (reloadTrigger && socket) {
|
||||
socket.on(reloadTrigger, handleReload);
|
||||
return () => {
|
||||
socket.off(reloadTrigger, handleReload);
|
||||
};
|
||||
}
|
||||
}, [url, socket, loadCounter]);
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user