How to use the react-apollo.renderToStringWithData function in react-apollo

To help you get started, we’ve selected a few react-apollo examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github strues / boldr / project / src / serverEntry.js View on Github external
const sheet = new ServerStyleSheet();

    const location = req.url;
    // appComponent takes the apolloClient, the reduxStore, location (req.url), the routerContext and
    // the  component.
    // It populates the ApolloProvider, StaticRouter and places the application component
    const appComponent = serverRender(
      { apolloClient, reduxStore, location, routerContext },
      ,
    );
    let markup = '';
    try {
      // render the applicaation to a string, collecting what's necessary to populate apollo's data and let styled-components
      // create stylesheet elements
      markup = await renderToStringWithData(sheet.collectStyles(appComponent));
    } catch (err) {
      console.error('Unable to render server side React:', err);
    }

    const chunkNames = flushChunkNames();
    console.log('[BOLDR] Flushing chunks...', chunkNames);

    const { scripts, stylesheets, cssHashRaw } = flushChunks(clientStats, {
      chunkNames: chunkNames,
      before: ['bootstrap', 'vendor'],
      after: ['main'],
      outputPath,
    });

    const finalState = {
      ...reduxStore.getState(),
github okgrow / advanced-graphql / ui / src / server.js View on Github external
}),
      cache,
    });

    // to be used by react-apollo
    const component = (
      
        
          
            
          
        
      
    );

    const content = await renderToStringWithData(component);

    const state = cache.extract();

    const styleTags = sheet.getStyleElement();

    const html = ;

    res.status(200);
    res.send(`\n${ReactDOM.renderToStaticMarkup(html)}`);
  } catch (e) {
    console.log(e);

    const component = (
      
        
          Server-side rendering error... Check the logs!
github VulcanJS / Vulcan / packages / vulcan-lib / lib / server / apollo-ssr / ssrMiddleware.js View on Github external
// this avoids caching server side
  const client = createClient(req);
  // TODO adapt to Vulcan
  const context = {};

  const App = appGenerator({ req, client, context })

  // Alternative that relies on Meteor server-render:
  // @see https://github.com/szomolanyi/MeteorApolloStarter/blob/master/imports/startup/server/ssr.js

  // TODO: adapt to Vulcan
  // @see https://github.com/apollographql/GitHunt-React/blob/master/src/server.js
  // @see https://www.apollographql.com/docs/react/features/server-side-rendering.html#renderToStringWithData
  // equivalent to calling getDataFromTree and then renderToStringWithData
  //sink.appendToBody(ReactDOM.renderToStaticMarkup(<div id="react-app"></div>))
  const content = await renderToStringWithData(App)
  console.log(content.slice(0,100))
  const wrappedContent = `<div id="react-app">${content}</div>`
  sink.appendToBody(wrappedContent)
  //sink.renderIntoElementById('react-app', 'HI')//content)
  // add headers
  const head = ReactDOM.renderToString(Head)
  sink.appendToHead(head)
  // add data
  const initialState = client.extract();
  sink.appendToBody(ReactDOM.renderToString(
github VulcanJS / Vulcan / packages / vulcan-lib / lib / server / apollo-ssr / renderPage.js View on Github external
// middlewares at this point
    // @see https://github.com/meteor/meteor-feature-requests/issues/174#issuecomment-441047495

    const App = ;

    // run user registered callbacks that wraps the React app
    const WrappedApp = runCallbacks({
      name: 'router.server.wrapper',
      iterator: App,
      properties: { req, context, apolloClient: client },
    });

    // equivalent to calling getDataFromTree and then renderToStringWithData
    let htmlContent = '';
    try {
    htmlContent = await renderToStringWithData(WrappedApp);
    } catch (err) {
      console.error(`Error while server-rendering. date: ${new Date().toString()} url: ${req.url}`); // eslint-disable-line no-console
      console.error(err);
      // show error in client in dev
      if (Meteor.isDevelopment) {
        htmlContent = `Error while server-rendering: ${err.message}`;
      }
    }

    // TODO: there should be a cleaner way to set this wrapper
    // id must always match the client side start.jsx file
    const wrappedHtmlContent = `<div id="react-app">${htmlContent}</div>`;
    sink.appendToBody(wrappedHtmlContent);
    // TODO: this sounds cleaner but where do we add the <div id="react-app"> ?
    //sink.renderIntoElementById('react-app', content)
</div>
github gaoxiaoliangz / readr / src / server / middleware / render / renderView.tsx View on Github external
return async (req, res) =&gt; {
    const { renderProps, statusCode } = req.locals.matchedResults
    const useServerRendering = process.env.ENABLE_SSR === '1'
    const appMarkup = (
      
    )
    let appMarkupString
    try {
      if (useServerRendering) {
        appMarkupString = await renderToStringWithData(appMarkup)
          .catch(err =&gt; {
            // todo: better way to handle error
            console.error(err)
          })
      } else {
        appMarkupString = renderToStaticMarkup(appMarkup)
      }
    } catch (error) {
      throw error
    }

    // 需要在 render 之后调用
    // 不调用 rewind 会造成内存泄漏
    const { bodyClass, head } = DocContainer.rewind()
    const initialState = process.env.ENABLE_INITIAL_STATE === '1'
      ? req.locals.store.getState()
github tigranpetrossian / hacker-news-redesigned / src / server / index.js View on Github external
`
    : ``;

  const gtag = `
    
    
  `;

  renderToStringWithData(jsx)
    .then((content) =&gt; {
      const initialState = client.extract();

      if (context.status) {
        res.status(context.status);
      }

      if (context.url) {
        return res.redirect(301, context.url);
      }

      res.send(`
github Setsun / react-koa-universal / src / server / middleware / useRender.tsx View on Github external
async function render ({ response }) {
    const css = fs.readFileSync('./dist/styles.css', 'utf8');
    const client = new ApolloClient({
      ssrMode: true,
      link: ApolloLink.from([]),
      cache: new InMemoryCache(),
    });

    renderToStringWithData(
      
        
      
    )
      .then(html =&gt; {
        const { critical, other }  = collect(html, css);

        response.status = 200;

        response.body = `
          
          
            
              <title>React Apollo Universal</title>
              
github Asing1001 / movieRater.React / src / server.tsx View on Github external
});

  const context = {}

  const app = (
    
      
        
      
    
  );

  renderToStringWithData(app).then(content =&gt; {
    const initialState = { apollo: client.getInitialState() };
    const page = swig.renderFile(staticRoot + 'bundles/index.html',
      {
        title: global.document.title,
        meta: global.document.meta,
        html: content,
        apolloState: ``
      });
    res.status(context["status"] || 200).send(page);
  }, error =&gt; next(error));
});
github DCtheTall / node-video-chat / src / server / routes / render.jsx View on Github external
async function render(req, res) {
  const link = new SchemaLink({ schema, context: req });
  const cache = new InMemoryCache();
  const apolloClient = new ApolloClient({ link, cache, ssrMode: true });
  const initialState = apolloClient.extract();
  const manifest = JSON.parse(readFileSync(path.join(__dirname, '../public/dist/manifest.json')));

  const App = createApp(req, apolloClient);
  const html = await renderToStringWithData();

  const token = req.cookies.get(process.env.COOKIE_KEY, { signed: true }) || '';

  res.render('index', {
    html,
    token: JSON.stringify(token),
    state: JSON.stringify(initialState).replace(/
github aredotna / ervell / src / v2 / apollo / ssr.tsx View on Github external
export const renderPageComponent = ({ client, Component, props = {} }) => {
  const sheet = new ServerStyleSheet();
  const helmetContext: any = {};
  const WrappedComponent = wrapWithProviders(client, helmetContext)(
    Component,
    props
  );

  return renderToStringWithData(sheet.collectStyles(WrappedComponent)).then(
    html => ({
      client,
      html,
      state: client.extract(),
      styles: sheet.getStyleElement(),
      helmet: helmetContext.helmet,
    })
  );
};