Skip to content

Commit ebb5fd2

Browse files
Merge pull request cerebral#498 from schiller-manuel/optional-action-param
feat(overmind): allow payload param of action to be optional
2 parents 6862975 + 3eb1964 commit ebb5fd2

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed

packages/node_modules/overmind/src/index.test.ts

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,23 @@ function createDefaultOvermind() {
4848
const changeValue = ({ actions }: Context, value: { isAwesome: boolean }) => {
4949
value.isAwesome = !value.isAwesome
5050
}
51+
const changeOptionalFoo = (context: Context, newFoo?: string) => {
52+
if (newFoo !== undefined) {
53+
context.state.foo = newFoo
54+
}
55+
else {
56+
context.state.foo = 'default-foo'
57+
}
58+
}
59+
const asyncChangeOptionalFoo = async (context: Context, newFoo?: string) => {
60+
await Promise.resolve()
61+
if (newFoo !== undefined) {
62+
context.state.foo = newFoo
63+
}
64+
else {
65+
context.state.foo = 'async-default-foo'
66+
}
67+
}
5168
const changeFormValue = (
5269
_: Context,
5370
payload: {
@@ -72,6 +89,8 @@ function createDefaultOvermind() {
7289
changeValue,
7390
waitAndChangeFoo,
7491
rehydrateAction,
92+
changeOptionalFoo,
93+
asyncChangeOptionalFoo
7594
}
7695
const effects = {
7796
hello() {
@@ -427,4 +446,19 @@ describe('Overmind', () => {
427446
changeFoo()
428447
expect(app.state.foo).toBe('replaced!')
429448
})
449+
test('should allow actions with optional parameter', async () => {
450+
const app = createDefaultOvermind()
451+
app.actions.changeOptionalFoo();
452+
expect(app.state.foo).toBe('default-foo')
453+
await app.actions.asyncChangeOptionalFoo();
454+
expect(app.state.foo).toBe('async-default-foo')
455+
456+
const newFoo = 'new-foo';
457+
app.actions.changeOptionalFoo(newFoo);
458+
expect(app.state.foo).toBe(newFoo)
459+
460+
const newAsyncFoo = 'new-async-foo';
461+
await app.actions.asyncChangeOptionalFoo(newAsyncFoo);
462+
expect(app.state.foo).toBe(newAsyncFoo)
463+
})
430464
})

packages/node_modules/overmind/src/internalTypes.ts

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -161,10 +161,14 @@ type NestedActions = {
161161

162162
export type ResolveAction<T> = T extends IOperator<void, infer R>
163163
? () => Promise<R>
164+
: T extends IOperator<infer P | undefined, infer R>
165+
? (payload?: P) => Promise<R>
164166
: T extends IOperator<infer P, infer R>
165167
? (payload: P) => Promise<R>
166168
: T extends IAction<void, infer R>
167169
? () => R
170+
: T extends IAction<infer P | undefined, infer R>
171+
? (payload?: P) => R
168172
: T extends IAction<infer P, infer R>
169173
? (payload: P) => R
170174
: T extends NestedActions

0 commit comments

Comments
 (0)