2023-05-18 13:17:41 +02:00
|
|
|
/*
|
|
|
|
|
* Copyright (C) Contributors to the Suwayomi project
|
|
|
|
|
*
|
|
|
|
|
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
|
|
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
|
|
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
|
|
|
*/
|
|
|
|
|
|
2022-11-02 10:42:02 +01:00
|
|
|
import { useEffect, useState } from 'react';
|
2023-08-15 13:54:29 +02:00
|
|
|
import requestManager from '@/lib/requests/RequestManager.ts';
|
2022-11-02 10:42:02 +01:00
|
|
|
|
|
|
|
|
const useSubscription = <T>(path: string, callback?: (newValue: T) => boolean | void) => {
|
|
|
|
|
const [state, setState] = useState<T | undefined>();
|
|
|
|
|
|
|
|
|
|
useEffect(() => {
|
2023-05-18 13:25:19 +02:00
|
|
|
const wsc = new WebSocket(requestManager.getValidWebSocketUrl(path));
|
2022-11-02 10:42:02 +01:00
|
|
|
|
|
|
|
|
wsc.onmessage = (e) => {
|
|
|
|
|
const data = JSON.parse(e.data) as T;
|
|
|
|
|
if (callback) {
|
|
|
|
|
// If callback is specified, only update state if callback returns true
|
|
|
|
|
// This is so that useSubscription can be used without causing rerender
|
|
|
|
|
if (callback(data) === true) {
|
|
|
|
|
setState(data);
|
|
|
|
|
}
|
|
|
|
|
} else {
|
|
|
|
|
setState(data);
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
return () => wsc.close();
|
|
|
|
|
}, [path]);
|
|
|
|
|
|
|
|
|
|
return { data: state };
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
export default useSubscription;
|