Skip to content

Commit

Permalink
fix(async-wrap): typings
Browse files Browse the repository at this point in the history
  • Loading branch information
fupengl committed Mar 5, 2022
1 parent 77957d8 commit 810fc53
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 12 deletions.
31 changes: 19 additions & 12 deletions src/components/async-wrap/index.tsx
Original file line number Diff line number Diff line change
@@ -1,26 +1,33 @@
import React, { useEffect, useState } from 'react';
import type { ReactNode } from 'react';
import { isFunction } from '@planjs/utils';
import React, { useEffect } from 'react';
import type { ReactNode, FC } from 'react';
import { isFunction, prefSetTimeout } from '@planjs/utils';

import useSafeState from '../../hooks/useSafeState';

export type AsyncWrapProps = {
delay?: number;
loaded?: (() => Promise<unknown>) | Promise<unknown>;
fallback: NonNullable<ReactNode> | null;
fallback?: ReactNode;
};

const AsyncWrap: React.FC<AsyncWrapProps> = (props) => {
const [loading, setLoading] = useState(true);
const AsyncWrap: FC<AsyncWrapProps> = (props) => {
const [loading, setLoading] = useSafeState(true);

useEffect(() => {
let timer: ReturnType<typeof setTimeout>;
if (props.loaded!) {
Promise.resolve(isFunction(props.loaded) ? props.loaded() : props.loaded).finally(() => {
timer = setTimeout(() => setLoading(false), props.delay || 0);
});
}
const timer = prefSetTimeout(() => {
if (props.loaded!) {
Promise.resolve(isFunction(props.loaded) ? props.loaded() : props.loaded).finally(() => {
setLoading(false);
});
} else {
setLoading(false);
}
}, props.delay || 0);

return () => {
timer && clearTimeout(timer);
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [props]);

return <>{loading ? props.fallback : props.children!}</>;
Expand Down
1 change: 1 addition & 0 deletions src/components/image/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ type ImageProps = React.ImgHTMLAttributes<HTMLImageElement> & {

const Image: React.FC<ImageProps> = ({ url, fallbackUrl, ...props }) => (
<img
alt=""
{...props}
src={url}
onError={(event) => {
Expand Down

0 comments on commit 810fc53

Please sign in to comment.