Expected state overwrite when calling a async action in child from within parent slice. #2511
-
Here's the scenario:
import { create } from "zustand";
import { immer } from "zustand/middleware/immer";
const parentSlice = (set) => ({
isParentActive: false,
setParentAndChildActive: () => set((state) => {
state.isParentActive = true;
state.setChildActive(); // <----- Even if the child is set to active with this call, it will be overwritten by the passed state parameter to set as it does not know about the updates made by childSlice
})
})
const childSlice = (set) => ({
isChildActive: false,
setChildActive: () => set((state) => {
state.isChildActive = true; // <----- This is being overwritten
}),
})
export const useStore = create(
immer((...a) => ({
...parentSlice(...a),
...childSlice(...a),
})),
); While I understand that this behavior might be expected, I'm looking for a solution to facilitate inter-slice communication and ensure that actions within the child slice are not overridden by those of the parent. Any guidance or suggestions on how to address this issue would be greatly appreciated. |
Beta Was this translation helpful? Give feedback.
Answered by
KamaniBhavin
Apr 27, 2024
Replies: 1 comment 2 replies
-
@KamaniBhavin as far I see what you are facing is the expected behavior I don't get what you are trying to do since parent and child share the same state |
Beta Was this translation helpful? Give feedback.
2 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@dbritto-dev
I see where you're coming from. That's why the title is "behaving as expected." I've identified a workaround by using "get" instead of "set" to call actions in another slice, which internally mutates the state. This seems to resolve the issue of overwriting.
I'll be wrapping up this discussion now. Thanks for the prompt response.