Dynamic import How do I import components

Based on the example here,

import("another-tool").then(({ default: thatTool }) => thatTool.go());

So how do I use this in React, I’m trying to use this in the return of the React hooks function,

function App(props) {
  return (
        <ErrorBoundary translation={value}>
            <GlobalContext.Provider value={value}>
                {import('/imports/ui/template/official/App').then(({default: Official}) => <Official/>)}
            </GlobalContext.Provider>
        </ErrorBoundary>
    );
}

Get a mistake, ask for help

=> Meteor server restarted
E20210212-20:45:48.255(8) (webapp_server.js:1065) Error running template: Error: Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead.

It’s a function, and I just execute it, just like in the example, and it returns the same error,

{import('/imports/ui/template/official/App').then(({default: Official}) => Official())}

Check out this post and the answers: Simple Dynamic Import of React Component from npm library

const ParentComponent = () => {
  const [ComponentA, setComponentA] = useState();
  useEffect(() => {
    import("@bla/A").then(setComponentA);
  }, []);
    return (
    <div>
      { ComponentA && <ComponentA /> }
    </div>
  )
}

Thank you for your quick reply. I have already used your method before sending this post, but it does not support SSR. Is dynamic import not supported by SSR?

I have consulted other people and they say that dynamic import supports SSR, so your method does work but the SSR is missing,

Any ideas

Official document guide, precious words like gold, if a little more context, I might understand, hahaha

I don’t have real-life experiences with SSR, so I may not be able to help.

However, check out @captainn’s Meteor-specific fork of react-loadable: GitHub - CaptainN/npdev-react-loadable: A Meteor port of the awesome react-loadable for webpack, which is supposed to work with SSR as well. He also created meteor-react-starter.

Most notably check out his exemplary server code where packages are also loaded dynamically.

The meteor-react-starter example only has a version of meteor,

There is no Apollo version, just tried again, his Apollo version, using React-loadable, not NPDV-React-loadable, and has been three years ago, no way to launch successfully

And he doesn’t seem to use Apollo, so for meteor+ Apollo, there’s no way to use NPDV-React loadable

So, now I try to use @nathanschwarz meteor-react-apollo-ssr example,

This example is perfect except for no code splitting and dynamic import. The core functionality is complete. I wanted to add a simple dynamic import on top of this, but unfortunately it didn’t work

Dynamic import was already available in meteor1.5. I think this is a simple function, isn’t it a common one? Does anyone tell me how to use and support SSR, am I the only one who needs SSR, lol, :flushed:

Somebody help me

There should be nothing stopping you from using Apollo with npdev:react-loadable - they are not packages which address similar problems. What specific problem have you had trying to add Apollo to my starter?

1 Like

Meteor + Apollo +npdev:react-loadable, git address not found

@captainn starter with apollo Instead of using npdev:react-loadable,
I just want a working example, without further ado, all in the wine

I never got around to make a starter with Apollo, but it shouldn’t be too much farther to travel to take any given Apollo SSR tutorial and make it work with my starter as a starting point. The techniques are all the same. Wrap the app in a Provider to capture data on the server, then serialize it before out put. Then on the client side, hydrate that data before rendering. My starter already has the bones, even if you need to flesh it out.

This is a complex and important enough aspect of any applications that I don’t recommend just deploying with someone’s starter without internalizing the workings of it. If anything goes wrong, you are going to want to know what’s going on.

2 Likes

You are right, I have been studying these days, to realize the dynamic import and SSR,

If my words are wrong, please forgive me, sometimes express the meaning of the translation software and you want to express the meaning of different, can only read the meaning is very good

Because of the meteor and Apollo involved, and the need for dynamic imports and SSR, I felt like I was trying a tough task

Your npdev:react-loadable is perfect without Apollo and that’s why it’s recommended

but

After the addition of Apollo, I have found two problems

The first one is, repeat rendering, which is a serious one, and I haven’t solved it yet,
The rendering process looks like this

The request data => server side return data => render => client request data return => render (page flicker)
Looking at the data request on the back end, the data is requested three times in a row

The second problem is that the current rendering route involves files that are not accurate enough and may contain files that are not used.
Well, I mentioned the question before and you answered it, but I didn’t understand it. However, it doesn’t matter much

Due to the problem of repeating the request for data 3 times in a row, I tried another example, which is perfect and has local caching effect.

The first request, the background read data 1 times
Refresh the page, the background will not read, directly from the slow access to the data

This is something I have never experienced before and have been using your package since

The request data => server side return data => render => client request data return => render (page flicker)
Looking at the data request on the back end, the data is requested three times in a row

I tried using Meteor’s dynamic import method to load files dynamically at the route level,
But the methods I know so far do not support SSR,

router.js

const Routes = (props) => {
    const staticRouter = [
        <Route exact path="/" component={Home} key="s1"/>,
    ];

    const [loading, setLoading] = useState(false);
    const [routes, setRoutes] = useState(staticRouter);
    const account = props.location.pathname === '/user/center';

    const dynamicRouter = async () => {
        setLoading(true);
        if (account) {
            const dynamic = await import('./event/dynamic');
            const resultRouter = dynamic.Generate(props);
            setRoutes([...staticRouter, ...resultRouter]);
        } else {
            setRoutes([...staticRouter]);
        }
        setLoading(false);
    }

    useEffect(async () => {
        await dynamicRouter();
    }, [account]);

    if (loading) {
        return <Loading/>
    }

    return (
        <Layout>
            <Switch>
                {routes}
                <Route component={NotFound} key='n1'/>
            </Switch>
        </Layout>
    )

./event/dynamic.js

import React from 'react';
import { Route } from 'react-router-dom';
import UCenter from '../../pages/UCenter';

export const Generate = props => {
    return [
        <Route path="/user/center" component={UCenter} {...props} key="d1"/>,
    ];
};

I will continue to research and feel closer to the truth

If the dynamic import cannot work with SSR, I will try to use your npdev:react-loadable to cooperate with Apollo again

Get to know this. This is the latest example meteor-react-apollo-ssr

If can take this example and combine it with your npdev: react-loadable to get a dynamic split and support SSR while still keeping the current functionality intact, that would be the perfect solution

The flicker problem is neither an issue with loadable nor apollo. It is an issue with how you hydrate the page in React

This discussion might help to expound

Thank you very much. Let me study it a little bit.

It’s more like:

  • request data

Server side:

  • Start SSR, and during SSR:
    • Capture used module list
    • Capture data (Apollo or Meteor or anything else)
  • Serialize captured data and used module list after SSR
  • Send SSRed HTML, serialized data, and module list to client

Client side:

  • Load module list
  • Parse and hydrate data
  • Hydrate React HTML

If you get these in the right order (and your “loading” code doesn’t block when data is already available), you’ll have no flashes. The specific technology you use for any given step is irrelevant (nor is the number of technologies you use). It just has to be done in the right sequence.

The challenge is that each of these steps is not that easy to set up… But it is all documented. You just have to work through it.

2 Likes

Thank you very much for your detailed explanation. I will study it more carefully