Feature/swr for library screens (#186)
* Wrap data fetching in library and manga screen with swr for better dev and user experience. Refactor some API calls and data handling. Add manual refresh to manga detail. * Fix manga card layout * Fix refresh button position on small screens * Revert "Fix manga card layout" This reverts commit d85da3d8385e1ef64feed1789e4cd4591c8bd563. * Fix manga not setting title * Move chapters loading to Manga component, join data fetching, add auto online fetch if fetched data is old * Revert some changes
This commit is contained in:
30
src/components/library/useSubscription.ts
Normal file
30
src/components/library/useSubscription.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
|
||||
const baseWebsocketUrl = JSON.parse(window.localStorage.getItem('serverBaseURL')!).replace('http', 'ws');
|
||||
|
||||
const useSubscription = <T>(path: string, callback?: (newValue: T) => boolean | void) => {
|
||||
const [state, setState] = useState<T | undefined>();
|
||||
|
||||
useEffect(() => {
|
||||
const wsc = new WebSocket(`${baseWebsocketUrl}${path}`);
|
||||
|
||||
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;
|
||||
Reference in New Issue
Block a user