Skip to content

Commit

Permalink
feat(lazycomponent): create useLazy hook
Browse files Browse the repository at this point in the history
replace <LazyComponent /> with useLazy on <Header /> when using <Sidebar />
  • Loading branch information
aneurysmjs committed Aug 4, 2019
1 parent caed285 commit f6f7131
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 11 deletions.
30 changes: 19 additions & 11 deletions src/app/components/core/Header/Header.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import React, { useState } from 'react';

import Icon from '@/components/base/Icon/Icon';
import Navigation from '@/components/core/Navigation/Navigation';
import Sidebar from '@/components/shared/Sidebar/Sidebar';
import { useLazy } from '@/components/shared/LazyComponent/LazyComponent';

import './Header.scss';

Expand All @@ -12,18 +12,26 @@ const Header = () => {

const handleOpen = () => setOpen(!open);

const Sidebar = useLazy(
() => import(/* webpackChunkName: "Sidebar" */'@/components/shared/Sidebar/Sidebar'),
open,
);

return (
<div className="header">
<Sidebar
isOpen={open}
onClose={handleOpen}
title="Cart"
side="right"
>
<p className="lead">
You have nothing, let&apos;s shop!
</p>
</Sidebar>
{Sidebar
? (
<Sidebar
title="Cart"
side="right"
isOpen={open}
onClose={handleOpen}
>
<p className="lead">
You have nothing, let&apos;s shop!
</p>
</Sidebar>)
: null}
<Navigation />
<div className="header__user-menu">
<span
Expand Down
23 changes: 23 additions & 0 deletions src/app/components/shared/LazyComponent/LazyComponent.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,3 +30,26 @@ const LazyComponent = ({ getModule, ...rest }: PropsType) => {
};

export default LazyComponent;

export const useLazy = (
getModule: () => Promise<*>,
cond?: boolean = false,
) => {
const [AsyncModule, setAsyncModule] = useState(null);
useEffect(() => {
(async () => {
try {
if (!cond) {
return;
}
const module = await getModule();
setAsyncModule(() => module.default);
} catch (err) {
throw new Error(`LazyComponent error: ${err}`);
}
})();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [cond]);

return AsyncModule;
};

0 comments on commit f6f7131

Please sign in to comment.