Skip to content

Commit 72c488e

Browse files
author
Victor Trusov
committed
Added isLoading props to the Switch component
1 parent 5538617 commit 72c488e

File tree

3 files changed

+20
-6
lines changed

3 files changed

+20
-6
lines changed

index.d.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,8 @@ declare module "react-router-loading" {
88
& OmitNative<T, keyof SwitchProps>
99
& {
1010
loadingScreen?: React.Component,
11-
maxLoadingTime?: number
11+
maxLoadingTime?: number,
12+
isLoading?: boolean
1213
},
1314
any
1415
> { }

src/LoadingMiddleware.jsx

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,10 @@
1-
import React, { useState, useMemo, useCallback } from 'react';
1+
import React, { useState, useMemo, useCallback, useEffect, useRef } from 'react';
22
import { LoadingContext, LoadingGetterContext } from './LoadingContext';
33
import { topbar } from '.';
44

5-
const LoadingMiddleware = ({ children }) => {
6-
const [loading, setLoading] = useState(false);
5+
const LoadingMiddleware = ({ children, isLoading = false }) => {
6+
const [loading, setLoading] = useState(isLoading);
7+
const isFirstRender = useRef(true);
78

89
const start = useCallback(() => {
910
topbar.show();
@@ -20,6 +21,18 @@ const LoadingMiddleware = ({ children }) => {
2021
topbar.show();
2122
}, []);
2223

24+
useEffect(() => {
25+
if (!isFirstRender.current) {
26+
// didn't use start() to skip unnecessary topbar triggering
27+
if (isLoading)
28+
setLoading(true);
29+
else
30+
done();
31+
} else {
32+
isFirstRender.current = false;
33+
}
34+
}, [isLoading]);
35+
2336
const loadingProvider = useMemo(
2437
() => <LoadingContext.Provider value={{ start, done, restart }}>
2538
{children}

src/LoadingSwitch.jsx

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -113,8 +113,8 @@ const RouteComponent = ({ context, allRoutes, hidden }) =>
113113
</div>;
114114

115115
// combine topbar and switch
116-
const LoadingSwitch = ({ children, loadingScreen, maxLoadingTime }) =>
117-
<LoadingMiddleware>
116+
const LoadingSwitch = ({ children, loadingScreen, maxLoadingTime, isLoading }) =>
117+
<LoadingMiddleware isLoading={isLoading}>
118118
<Switcher loadingScreen={loadingScreen} maxLoadingTime={maxLoadingTime}>
119119
{children}
120120
</Switcher>

0 commit comments

Comments
 (0)