-
Notifications
You must be signed in to change notification settings - Fork 48
Open
Description
I wan to load some components by a fetch result, such as:
// registryComponent.js
import { createRequires, fetchRemoteComponent, getServerSideProps as getProps } from "@paciolan/remote-component";
import dynamic from "next/dynamic";
import config from "./remote-component.config";
const requires = createRequires(config.resolve);
export function registryComponents(urls: { url: string; name: string }[] = []): Record<string, any> {
const compoents: Record<string, any> = {};
for (let i = 0; i < urls.length; i++) {
const c = urls[i];
compoents[c.name] = dynamic(() => fetchRemoteComponent({ url: c.url, requires }));
}
return compoents;
}
export function getComponentRequest(
urls: { url: string; name: string }[] = [],
data: any,
context?: any
): Promise<unknown>[] {
const requests: Promise<unknown>[] = [];
for (let i = 0; i < urls.length; i++) {
const c = urls[i];
requests.push(
getProps({
url: c.url,
requires,
context: { ...context, data },
})
);
}
return requests;
}// next.js Page
import React from "react";
import { registryComponents, getComponentRequest } from "./registryComponent";
class HelloWorld extends React.Component {
comps = {};
static async getInitialProps(ctx: any): Promise<any> {
const data = { id: 1 };
const urls = await fetch("http://mockhttp.cn/mock/components", { method: "GET" }).then((res) => res.json());
// return components's request Promise
const requests = getComponentRequest(urls, data, ctx);
// return components
const dyComp = registryComponents(urls);
// waiting request finish.
const compData = await Promise.all(requests);
return { jsonData: urls, compData, dyComp };
}
render(): JSX.Element {
const { jsonData, compData, dyComp } = this.props;
return (
<div>
{dyComp &&
Object.keys(dyComp).length &&
jsonData &&
jsonData.map((item: any, index: number) => {
const DynamicComponent = dyComp[item.name];
return <DynamicComponent key={item.name} data={compData[index]} />;
})}
</div>
);
}
}The question is in nextjs getInitialProps dyComp can't be translate to JSON. so it can not work.
on browser console, console.log(dyComp) ==> {table: {}, button: {}}
Do you have a good idea?
Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
No labels