Skip to content

Commit

Permalink
Merge pull request #17735 from saiichihashimoto/type-useArgs-1
Browse files Browse the repository at this point in the history
Core: Typing useArgs
  • Loading branch information
ndelangen authored Jul 2, 2022
2 parents 208e893 + 8f8213f commit 013770d
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 10 deletions.
Original file line number Diff line number Diff line change
@@ -1,8 +1,20 @@
import React, { useState } from 'react';
import React, { FC, useState } from 'react';
import { useArgs } from '@storybook/client-api';

// eslint-disable-next-line react/prop-types
const ArgUpdater = ({ args, updateArgs, resetArgs }) => {
interface CustomArgs {
first?: string;
last?: string;
foo?: string;
}

type UpdateArgs = ReturnType<typeof useArgs>[1];
type ResetArgs = ReturnType<typeof useArgs>[2];

const ArgUpdater: FC<{ args: CustomArgs; updateArgs: UpdateArgs; resetArgs: ResetArgs }> = ({
args,
updateArgs,
resetArgs,
}) => {
const [argsInput, updateArgsInput] = useState(JSON.stringify(args));

return (
Expand Down Expand Up @@ -30,7 +42,7 @@ export default {
title: 'Core/Args',
decorators: [
(story) => {
const [args, updateArgs, resetArgs] = useArgs();
const [args, updateArgs, resetArgs] = useArgs<CustomArgs>();

return (
<>
Expand Down Expand Up @@ -63,14 +75,14 @@ export const DifferentSet = Template.bind({});
DifferentSet.args = {
foo: 'bar',
bar: 2,
};
} as CustomArgs;

export const TestUndefinedArgs = Template.bind({});
TestUndefinedArgs.args = {
first: 'Bob',
last: 'Miller',
foo: 'bar',
};
} as CustomArgs;
TestUndefinedArgs.argTypes = {
first: {
control: { type: 'select' },
Expand Down
8 changes: 4 additions & 4 deletions lib/addons/src/hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -424,21 +424,21 @@ export function useParameter<S>(parameterKey: string, defaultValue?: S): S | und
}

/* Returns current value of story args */
export function useArgs(): [Args, (newArgs: Args) => void, (argNames?: [string]) => void] {
export function useArgs<SpecificArgs = Args>(): [SpecificArgs, (newArgs: Partial<SpecificArgs>) => void, (argNames?: (keyof SpecificArgs)[]) => void] {
const channel = addons.getChannel();
const { id: storyId, args } = useStoryContext();

const updateArgs = useCallback(
(updatedArgs: Args) => channel.emit(UPDATE_STORY_ARGS, { storyId, updatedArgs }),
(updatedArgs: Partial<SpecificArgs>) => channel.emit(UPDATE_STORY_ARGS, { storyId, updatedArgs }),
[channel, storyId]
);

const resetArgs = useCallback(
(argNames?: [string]) => channel.emit(RESET_STORY_ARGS, { storyId, argNames }),
(argNames?: (keyof SpecificArgs)[]) => channel.emit(RESET_STORY_ARGS, { storyId, argNames }),
[channel, storyId]
);

return [args, updateArgs, resetArgs];
return [args as SpecificArgs, updateArgs, resetArgs];
}

/* Returns current value of global args */
Expand Down

0 comments on commit 013770d

Please sign in to comment.