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-fetching-components

v0.1.1

Published

Asynchronously load data for your React components with SSR

Downloads

6

Readme

This package allows you to add a getInitialData method to your React components, no matter how deeply they are nested. It also works seamlessly with Server-Side Rendering and rehydration.

Installation

yarn install react-data-fetching-components

Usage

Wrap any components you want to fetch data for with the withInitialData HOC, and add a static method getInitialData to the class. This method should return a Promise, or be set to an async function. Here's an example component;

import React, { Component } from 'react';
import { withInitialData } from 'react-data-fetching-components';

class Page extends Component {
  static async getInitialData(props) {
    const res = await fetch('...');
    const json = await res.json();

    return json;
  }

  render() {
    return <div>{this.props.data}</div>;
  }
}

export default withInitialData(Page);

Loading and Error States

You can also add loading and error methods on your component, alongside render, that will display when getInitialData is either pending or rejects. For example;

import React, { Component } from 'react';
import { withInitialData } from 'react-data-fetching-components';

class Page extends Component {
  static async getInitialData(props) {
    const res = await fetch('...');
    const json = await res.json();

    return json;
  }

  loading() {
    return <div>Loading data...</div>;
  }

  error() {
    return <div>Error loading data!</div>;
  }

  render() {
    return <div>{this.props.data}</div>;
  }
}

export default withInitialData(Page);

Server-Side Rendering

Setup

To get SSR working, you just need to edit two files. First, edit your server.js file by awaiting on getAllInitialData before rendering your top-level app component. Then, when you're ready to renderToString, wrap the app component with <ComponentDataStore data={data}> to pass in the data that has been pre-fetched. It should look something like this pseudocode;

import {
  ComponentDataStore,
  getAllInitialData
} from 'react-data-fetching-components';

server.get('/*', async (req, res) => {
  const app = <App />;

  const data = await getAllInitialData(app);

  const markup = renderToString(
    <ComponentDataStore data={data}>{app}</ComponentDataStore>
  );

  res.status(200).send(`<html>
    <body>
      ${markup}
    </body>
  </html>`);
});

Then, in your HTML response, you should add the following script tag before your JS assets;

<script>window._COMPONENT_DATA_ = ${JSON.stringify(data)};</script>

Now, edit your client.js file by adding the <ComponentDataStore> component and passing in the data from window._COMPONENT_DATA_ like so;

import { ComponentDataStore } from 'react-data-fetching-components';

const data = window._COMPONENT_DATA_;

hydrate(
  <ComponentDataStore data={data}>
    <App />
  </ComponentDataStore>,
  document.getElementById('root')
);

This allows the client-side app to seamlessly rehydrate the data loaded during your server request.

Advanced: Parallelising Network Requests

By default, every time you server-render a component that has getInitialData, rendering is paused until that method's Promise is completed. This means that this.props.data is always available by the time the render method is fired. However, if you have a lot of nested components making network requests, your page load times will start to get noticeably slower, as every request is happening sequentially. Fortunately, there's a solution! Here's an example component;

class ParallelComponent extends Component {
  static getInitialDataInParallel = true;

  static async getInitialData(props) {
    const res = await fetch('...');
    const json = await res.json();

    return json;
  }

  render() {
    return <div>{this.props.data ? this.props.data : null}</div>;
  }
}

By setting the getInitialDataInParallel property on your component class to true, during the server-render pass the getInitialData Promise will be pushed to an array and later fired in parallel with Promise.all. The main caveat for your component is that now, in your render method, you must include a conditional check for this.props.data, as it will not be defined during the initial render pass.

This is ideal for cases where you have a nested component that makes a data request, but does not depend upon the result of a data request higher up the component tree, e.g. it can rely purely on routing params.