Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save localStorage per story in storybook

Is it possible to save something to localStorage/sessionStorage per story and/or per stories file?

Is there any addon for this, I can't find any

I would expect something like

Default.parameters = {
    sessionStorage: {
        userId: '123'
    }
};
like image 798
Israel kusayev Avatar asked Oct 14 '25 16:10

Israel kusayev


1 Answers

First, customize your story to use a one-off loader in order to initialize it with some custom local/session storage set up.

// your story definition

export const SomeStory = () => {
  return <SomeComponent />;
};
SomeStory.loaders = [
  () => {
    window.localStorage.setItem("somekey", "somevalue");
    window.sessionStorage.setItem("somekey", "somevalue");
  },
];

However, your browser storage (local/session/otherwise) will not be isolated between stories.

You can add a global decorator to reset the storage in between stories to your preview file.

// in preview.tsx

const browserStorageResetDecorator: DecoratorFn = (Story) => {
  window.localStorage.clear();
  window.sessionStorage.clear();
  return <Story />;
};

export const decorators: DecoratorFn[] = [
   browserStorageResetDecorator
];

There are other ways to do global decorators, this is just my preference.

See storybook docs for more information.

like image 194
boylec1986 Avatar answered Oct 19 '25 14:10

boylec1986



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!