frintjs / frint

Modular JavaScript framework for building scalable and reactive applications
https://frint.js.org/
MIT License
756 stars 37 forks source link

frint-react: `observe` HoC can return props synchronously #339

Closed fahad19 closed 6 years ago

fahad19 commented 6 years ago

Closes #338

What's done

observe higher-order component can now return props synchronously too, which helps in server-side rendering.

Usage

If the beginning of your Component file looks like this:

// components/MyComponent.js
import React from 'react';
import { observe } from 'frint-react';

const MyComponent(props) {
  return <p>App name: {props.name}</p>;
}

You can do the final export in either of the ways:

Streaming props

import { Observable } from 'rxjs';

export default observe(function (app) {
  return Observable.of({
    name: app.getName(),
  });
})(MyComponent);

Synchronous props

export default observe(function (app) {
  return {
    name: app.getName(),
  };
})(MyComponent);

Server-side usage

Like mentioned in #338, combining environment variables usage in the server along with Webpack's DefinePlugin in the bundler, the final export can look like this:

import { Observable } from 'rxjs';

export default observe(function (app) {
  // sync (for the server)
  if (process.env.BABEL_ENV === 'server') {
    return {
      name: app.getName(),
    };
  }

  // streaming props (for the bundle)
  return Observable.of({
    name: app.getName(),
  });
})(MyComponent);
coveralls commented 6 years ago

Coverage Status

Coverage increased (+0.01%) to 97.476% when pulling d260fd7278876e8b3b74fe538ce57473895e44b2 on sync-observe into 916f44c2587ccce2fc9529ae83d3066d4fbf7a68 on master.