DattaIT
DattaIT

Reputation: 1

How to create a typed component that given some data renders it when all data is available

I am trying to create a component that looks something like this:

type FN = (...params: any[]) => React.ReactNode;

export type LoaderProps<T extends FN> = {
  data: Partial<Parameters<T>>;
  onRender: T;
};

export default function Loader<T extends FN>({
  data,
  onRender,
}: LoaderProps<T>) {
  const isLoaded = data.every((d) => d !== undefined);
  return (
    <>
      <SplashScreen loading={!isLoaded} />
      {isLoaded && (
        <div>
          {onRenderChildren(...(data as Parameters<T>))}
        </div>
      )}
    </>
  );
}

The problem is when I use the component, it's all backwards. I will need to define the onRender function first and then add my asyn data.

const asyncData = useGetAsyncDate(); // Can be undefined
<Loader data={[asyncData]} onRender=((data: AsyncData) => <MyComponentUsingAsyncData data={data} />)/>

Would it be possible with some TS magic to define the data and then get the onRender typed as it should?

Upvotes: 0

Views: 30

Answers (0)

Related Questions