Working with React's useContext via Storybook

1.6k views Asked by At

I'm trying to access data in the contextAPI via storybook but I couldn't manage it. Please, keep in mind that there isn't any issue with the original pages, the context is working properly.

React version: 17.0.2 Storybook version: 6.2.7 Here is the devDep:

"devDependencies": {
    "@storybook/addon-actions": "^6.2.7",
    "@storybook/addon-essentials": "^6.2.7",
    "@storybook/addon-links": "^6.2.7",
    "@storybook/node-logger": "^6.2.7",
    "@storybook/preset-create-react-app": "^3.1.7",
    "@storybook/react": "^6.2.7",
    "eslint-config-react-app": "^6.0.0",
    "eslint-plugin-prettier": "^3.3.1",
    "eslint-plugin-react": "^7.23.1",
    "eslint-plugin-react-hooks": "^4.2.0",
    "node-sass": "^5.0.0",
    "prettier": "^2.2.1",
    "sass": "^1.32.8"
}

I've added a decorator for the wrapper in preview.js file of Storybook.

addDecorator((storyFn) => <GlobalStore>{storyFn()}</GlobalStore>);

Then, in the X.stories.js, I'm trying to call useContext as usual:

import { GlobalContext } ...
import { useContext } ...

export const SampleStory = () => {
const { Variable } = useContext(GlobalContext);

But I'm am facing this error in the story:

Cannot read property 'Variable' of undefined

As a solution, I created a new component as a new/separated file and imported it through X.stories.js. This solution works but in this way, I have to create lots of unnecessary files which is useless.

Can you please tell me the correct way for that issue?

Thanks in advance, Cheers,

0

There are 0 answers