storybook: fix lockup issue related to react-query invalidation

PR-URL: https://github.com/hasura/graphql-engine-mono/pull/9234
GitOrigin-RevId: 14beecb1626369f92362adb4d2c130b25ed53109
This commit is contained in:
Matthew Goodwin 2023-05-22 11:36:54 -05:00 committed by hasura-bot
parent 230e8a8cad
commit e51d1cf936

View File

@ -1,28 +1,31 @@
import { DecoratorFn } from '@storybook/react';
import { useEffect } from 'react';
import { QueryClient, QueryClientProvider, useQueryClient } from 'react-query';
import { Decorator } from '@storybook/react';
import React from 'react';
import { QueryClient, QueryClientProvider } from 'react-query';
import { ReactQueryDevtools } from 'react-query/devtools';
import useUpdateEffect from '../../hooks/useUpdateEffect';
export const ReactQueryDecorator = (): DecoratorFn => {
const reactQueryClient = new QueryClient();
export const ReactQueryDecorator = (): Decorator => {
return Story => (
<QueryClientProvider client={reactQueryClient}>
<QueryInvalidator />
<ReactQueryProvider>
<Story />
<ReactQueryDevtools />
</QueryClientProvider>
</ReactQueryProvider>
);
};
const QueryInvalidator = () => {
const client = useQueryClient();
useEffect(() => {
return () => {
client.invalidateQueries();
};
}, []);
// you can't use hooks directly in a Decorator function, so we need to encapsulate this in a component
const ReactQueryProvider: React.FC = ({ children }) => {
let reactQueryClient = new QueryClient();
return null;
useUpdateEffect(() => {
// re-render happens only on story change or HMR. in those cases we want a fresh instance of the query client so we don't end up with stale cache
// invalidating queries is buggy due to async behavior and can cause storybook to lock up.
// so, this is the safest approach.
reactQueryClient = new QueryClient();
});
return (
<QueryClientProvider client={reactQueryClient}>
{children}
</QueryClientProvider>
);
};