Skip to content

Instantly share code, notes, and snippets.

@gsasouza
Last active March 24, 2020 19:53
Show Gist options
  • Save gsasouza/ad1072033389b621331c894ddb91741a to your computer and use it in GitHub Desktop.
Save gsasouza/ad1072033389b621331c894ddb91741a to your computer and use it in GitHub Desktop.
import * as React from 'react';
import { useLocation } from 'react-router-dom';
import { graphql, usePreloadedQuery, useEnvironment } from 'react-relay/hooks';
const Comp1 = React.lazy(() => import('./Comp1'));
const Comp2 = React.lazy(() => import('./Comp2'));
const Comp3 = React.lazy(() => import('./Comp3'));
const Query = graphql`
query RootQuery(
$fetchComp1: Boolean = false
$fetchComp2: Boolean = false
$fetchComp1: Boolean = false
) {
...Comp1_query @include(if: $fetchComp1)
...Comp2_query @include(if: $fetchComp2)
...Comp3_query @include(if: $fetchComp3)
}
`;
const getComponent = () => {
if (condition1) return Comp1;
if (condition2) return Comp2;
return Comp3;
};
const getVariables = () => {
if (condition1) return { fetchComp1: true };
if (condition2) return { fetchComp2: true };
return return { fetchComp3: true };
};
const Root = ({ preloadedQuery, ...props }) => {
const query = usePreloadedQuery(Query, preloadedQuery);
const Component = getComponent();
if (!Component) return null;
return (
<React.Suspense fallback={<Loading />}>
<Component {...props} query={query} />
</React.Suspense>
);
};
const RootWithQuery = (props) => {
const environment = useEnvironment();
const preloadedQuery = preloadQuery(environment, Query, getVariables())
return <Root {...props} preloadedQuery={preloadedQuery} />
};
export default RootWithQuery;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment