How to save localStorage per story in storybook

1.9k views Asked by At

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'
    }
};
2

There are 2 answers

1
Adama Camara On

A neat solution I found was to actually store item to local storage before returning your story component.

0
boylec1986 On

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.