npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

react-data-ssr-server

v1.2.0

Published

Server side initial data resolution for react-data-ssr

Downloads

12

Readme

React Data SSR

Server side initial data resolution for react-data-ssr.

Instalation

yarn -i react-data-ssr-server

# Or using npm
npm -i react-data-ssr-server --save

Examples

The examples folder contains several exmaples.


Usage

Simple Example

// server.js
import express from 'express';
import React from 'react';
import { renderToString } from 'react-dom/server';
import { resolveInitialData } from 'react-data-ssr';
import { matchRoutes, renderRoutes } from 'react-router-config';
import { StaticRouter } from 'react-router';
import routes from './routes'; // React Router Config Routes
import serialize from 'serialize-javascript';

const server = express();
server
  .get('/*', (req, res) => {
    // Get all the branches
    const branches = matchRoutes(routes, req.url);

    // Resolve the data required by each branch
    resolveInitialData(branches)
      .then(({store, errors}) => {
        // We'll ignore errors

        const context = {};

        // Render the markup
        const markup = renderToString(
          <StaticRouter location={req.url} context={context}>
            {renderRoutes(routes, {
              getInitialData: k => store[k],
              hasLoadedComponent: k => k in store,
              dismissLoadedComponent: () => console.trace('Should not call `dismissLoadedComponent` in SSR`'),
            })}
          </StaticRouter>
        );

        res.send(
          `<!doctype html>
          <html lang="">
          <head>
            <meta httpEquiv="X-UA-Compatible" content="IE=edge" />
            <meta charSet='utf-8' />
            <title>React Data SSR example</title>
            <meta name="viewport" content="width=device-width, initial-scale=1">
            ${assets.client.css
              ? `<link rel="stylesheet" href="${assets.client.css}">`
              : ''}
             ${process.env.NODE_ENV === 'production'
               ? `<script src="${assets.client.js}" defer></script>`
               : `<script src="${assets.client.js}" defer crossorigin></script>`}
          </head>
          <body>
            <div id="root">${markup}</div>
            <script>
              window.__INITIAL_DATA__ = ${serialize(store)}
            </script>
          </body>
          </html>`
        );
      });
  });

Note: The example uses React 16, but it's not a requeriment. React 15 could alse be used. Note 2: The example uses React Router Config, but it's not a requeriment. Any route configuration could be used.

Api

resolveInitialData(branches, extra) -> Promise

Resolves all data, calling the static method getInitialData of each branch's component.

branches

List with branches. This function support 3 types of branches:

  • React Router Config: What is returned by the matchRoutes function. Eg:
{
  route: {
    component: Component,
    routes: []
  },
  match: {
    path: '',
    url: '',
    params: {},
    isExact:
  }
}
  • Dictionary: A dictionary with a key component that contains the react component. Eg:
{
  component: Component,
  // ...
}
  • Component: Just the React Component.

Note: Remember that the branch will be passed as an argument to the static method getInitialData. By using the mapArgsToProps this args can be mapped to the required props for the getData.

extra

This is an extra, optional argument that will be passed to getInitialData. It can be used in the mapArgsToProps to map properties getData.

Returned value (Promise)

The function returns a Promise that will be resolved when all the getInitialData promises resolve.

In the resolution, this promise sends an Object with two keys:

  • store: A dictionary that relates successful getInitialData's promises (by the Component's Key) with the resolved data.
  • errors: A dictionary that relates the rejected getInitialData's promises (by the Component's key) with the failed data.

Note: This promise will never reject