Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/fix-function-options.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'zustand-x': patch
---

Fix assigning function-valued options so callbacks still work.
11 changes: 8 additions & 3 deletions packages/zustand-x/src/internal/createBaseApi.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
import { StoreMutatorIdentifier } from 'zustand';

import { TBaseStateApiForBuilder, TStoreApiGet } from '../types/baseStore';
import { TState } from '../types/utils';
import { TCreatedStoreMutateType } from '../types/utils';
import { TCreatedStoreMutateType, TState } from '../types/utils';

import type {
AnyFunction,
Expand Down Expand Up @@ -44,7 +43,13 @@ export const createBaseApi = <
const typedKey = key as keyof StateType;
const prevValue = store.getState()[typedKey];

if (typeof value === 'function') {
const shouldInvokeUpdater =
typeof value === 'function' &&
prevValue !== undefined &&
prevValue !== null &&
typeof prevValue !== 'function';

if (shouldInvokeUpdater) {
value = value(prevValue);
}
if (prevValue === value) return;
Expand Down
37 changes: 37 additions & 0 deletions packages/zustand-x/src/tests/createStore.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,43 @@ describe('zustandX', () => {
expect(starsListener).toHaveBeenCalledTimes(2);
expect(starsListener).toHaveBeenLastCalledWith(3, 0);
});

it('should support callback updates for primitive values', () => {
expect(store.get('stars')).toBe(0);
store.set('stars', (currentStars) => currentStars + 5);
expect(store.get('stars')).toBe(5);
store.set('state', {
name: 'zustandX',
stars: 0,
});
});

it('should store function values without invoking them', () => {
type FunctionStoreState = {
handler: () => string;
optionalHandler: ((value: number) => number) | null;
};

const functionStore = createStore<FunctionStoreState>(
{
handler: () => 'initial',
optionalHandler: null,
},
{
name: 'function-store',
}
);

const newHandler = vi.fn(() => 'updated');
expect(() => functionStore.set('handler', newHandler)).not.toThrow();
expect(functionStore.get('handler')).toBe(newHandler);
expect(newHandler).not.toHaveBeenCalled();

const nextOptional = vi.fn((value: number) => value * 2);
functionStore.set('optionalHandler', nextOptional);
expect(functionStore.get('optionalHandler')).toBe(nextOptional);
expect(nextOptional).not.toHaveBeenCalled();
});
});

describe('when using hooks', () => {
Expand Down