Advanced usage of set for ignoring state changes
See original GitHub issueIt would be nice if we could ignore state on a granular level, for any state change.
Perhaps you have a piece of state that changes very often and you only want to store those changes occasionally. One example would be the a rotation property on a 3D object. Perhaps there is an app where the user can rotate 3D objects. These update every frame but you only want to store the beginning and end state of the user’s rotation. It might be convenient to have this information in the store, but without ignoring most of the changes, you’ll have to click “undo” 100 times just to get back to the beginning of the rotation!
This could be solved by adding an extra argument to the step function:
const useStoreWithUndo = create<StoreState>(set => ({
rotationX: 0,
...
setRotation: (rotationX) => set(state => ({ rotationX })),
setRotationWithIgnore: (rotationX) => set(state => ({ rotationX }), true), // Set second arg to true to ignore this change
}));
In a more complex scenario, you may want to use current state to determine whether to set this argument:
const useStoreWithUndo = create<StoreState>((set, get) => ({
...
setRotation: (rotationX) => {
const shouldIgnore = get().isDragging
return set(state => ({ rotationX }), shouldIgnore)
}
}));
I’m not entirely sure if this is the best API but thought I’d share my thoughts on the problem and a possible solution.
Issue Analytics
- State:
- Created 2 years ago
- Reactions:1
- Comments:9 (5 by maintainers)
I think an option to enable/disable this feature would be the safest approach. The hard part now is just getting typescript to play nicely with other middlewares 😵💫
I can review your code later this weekend. Thanks!