Skip to content

How can I load all components by fetch result with nextjs? #34

@Evansy

Description

@Evansy

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?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions