Nested slice
#2970
Replies: 1 comment 5 replies
-
@armpogart I saw some issues here, that code could cause infinite loop useEffect(() => {
const handler = () => console.log('ws message received');
if (subscribe) {
socket.on(`conversation/${id}`, handler);
slice.setSubscribed(true);
}
return () => {
if (subscribe && slice.subscribed) {
socket.off(`conversation/${id}`, handler);
slice.setSubscribed(false);
}
};
}, [id, slice, socket, subscribe]); |
Beta Was this translation helpful? Give feedback.
5 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
I'm trying to implement some sort of nested slice. Below is minimal reproduction of what I'm doing. For simplicity all other slices are removed.
slices/chat.ts
slices/chats.ts
index.ts
initChats
action is used in loader to fetch and initialized the conversations, it's doing it's job as intended.Now after that I have the folllowing selector (hook):
selectors/chat.ts
useSocket
is fromContext
and holds socket connection and is working correct outside of this code.zustand
.useChat
selector/hook, as far as I see it's working correct initially, but as soon as I do some local change on files and HMR triggers (I'm usingvite.js
), I'm getting the following error:Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate.
. I guess that happens on unmount, when theuseEffect
return is called in my hook andslice.setSubscribed(false)
is done. Do I have some unstable selector output, why does that happen?Any help is appreciated!
Update 1:
selectors/chat.ts
Now with this modified version, where I've tried to make the selectors stable. I'm seeing double subscription (the
console.log
message) and I never see unsubscription, theuseEffect
return is called, butsubscribed
is never true there. As soon as I modify the return conditionif (subscribe) ....
removingsubscribed
, I'm immediately getting infinite loop (the mentioned error).Beta Was this translation helpful? Give feedback.
All reactions