Vencord/src/utils/lazyReact.tsx

40 lines
1.1 KiB
TypeScript
Raw Normal View History

/*
* Vencord, a Discord client mod
* Copyright (c) 2023 Vendicated and contributors
* SPDX-License-Identifier: GPL-3.0-or-later
*/
2023-11-25 01:55:59 +00:00
import { ComponentType } from "react";
import { makeLazy } from "./lazy";
2024-05-03 02:18:12 +00:00
export const NoopComponent = () => null;
/**
* A lazy component. The factory method is called on first render.
2024-05-03 02:18:12 +00:00
* @param factory Function returning a component
* @param attempts How many times to try to get the component before giving up
* @returns Result of factory function
*/
export function LazyComponent<T extends object = any>(factory: () => React.ComponentType<T>, attempts = 5) {
const get = makeLazy(factory, attempts);
2024-05-03 02:18:12 +00:00
let failed = false;
const LazyComponent = (props: T) => {
2024-05-03 02:18:12 +00:00
const Component = get() ?? (() => {
if (!failed) {
failed = true;
console.error(`LazyComponent factory failed:\n${factory}`);
}
return NoopComponent;
})();
return <Component {...props} />;
};
2024-05-03 02:18:12 +00:00
LazyComponent.$$vencordGetter = get;
2023-11-25 01:55:59 +00:00
return LazyComponent as ComponentType<T>;
}