Browse Source

unsubscribe from websocket while revalidating posts

main
Dash8 5 months ago
parent
commit
b9afed92b6
  1. 58
      src/components/main.tsx

58
src/components/main.tsx

@ -146,15 +146,23 @@ function Main(props) {
const immutFetcher = url => api.get(url).then(res => List(res.data.posts));
const { data: postList, mutate: postListMutate } = useSWR(
const {
data: postList,
mutate: postListMutate,
isValidating: postListValidating,
} = useSWR(
dataType === DataType.Post ? `post/list?${params.toString()}` : null,
immutFetcher,
{
revalidateOnFocus: false,
}
) as { data: List<Post>; mutate: any };
) as { data: List<Post>; mutate: any; isValidating: boolean };
const { data: featuredPostList, mutate: featuredPostListMutate } = useSWR(
const {
data: featuredPostList,
mutate: featuredPostListMutate,
isValidating: featuredPostListValidating,
} = useSWR(
dataType === DataType.Post
? `post/featured${
UserService.Instance.auth ? `?auth=${UserService.Instance.auth}` : ''
@ -164,7 +172,7 @@ function Main(props) {
{
revalidateOnFocus: false,
}
) as { data: List<Post>; mutate: any };
) as { data: List<Post>; mutate: any; isValidating: boolean };
params = new URLSearchParams({
type_: ListingType[listingType],
@ -180,13 +188,17 @@ function Main(props) {
const commentFetcher = url =>
api.get(url).then(res => List(res.data.comments));
const { data: commentsList, mutate: commentsListMutate } = useSWR(
const {
data: commentsList,
mutate: commentsListMutate,
isValidating: commentsListValidating,
} = useSWR(
dataType === DataType.Comment ? `comment/list?${params.toString()}` : null,
commentFetcher,
{
revalidateOnFocus: false,
}
) as { data: List<Comment>; mutate: any };
) as { data: List<Comment>; mutate: any; isValidating: boolean };
const parseMessage = useCallback(
(msg: WebSocketJsonResponse) => {
@ -341,18 +353,34 @@ function Main(props) {
}, []);
useEffect(() => {
let subscription = WebSocketService.Instance.subject
.pipe(retryWhen(errors => errors.pipe(delay(3000), take(10))))
.subscribe(
msg => parseMessage(msg),
err => console.error(err),
() => console.log('complete')
);
let subscription;
if (
!(
commentsListValidating ||
postListValidating ||
featuredPostListValidating
)
) {
subscription = WebSocketService.Instance.subject
.pipe(retryWhen(errors => errors.pipe(delay(3000), take(10))))
.subscribe(
msg => parseMessage(msg),
err => console.error(err),
() => console.log('complete')
);
}
return () => {
subscription.unsubscribe();
if (subscription) {
subscription.unsubscribe();
}
};
}, [parseMessage]);
}, [
parseMessage,
commentsListValidating,
postListValidating,
featuredPostListValidating,
]);
//whenever props updates
useEffect(() => {

Loading…
Cancel
Save