5.0.0 • Published 6 years ago

react-service v5.0.0

Weekly downloads
2
License
MIT
Repository
github
Last release
6 years ago

React Service Component

React Service Component allows run services on client an server sides

NPM version Downloads Build Status

Usage

App.js

import React, { Component } from 'react';
import withService from 'react-service';

const service: postId => fetch(`https://jsonplaceholder.typicode.com/posts/${postId}`)
                            .then(response => response.json());

@withService(service, { mapParams: props => props.post })
export default class App extends Component {
  render() {
    const { data: { loading, result, error } } = this.props;
    if (loading && !result) {
      return <div>Loading...</div>;
    }
    if (error) {
      return <div>{error}</div>;
    }
    return (
      <div>
        <h1>{result.title}</h1>
        <p>{result.body}</p>
      </div>
    );
  }
}

client.js

import React from 'react';
import { hydrate } from 'react-dom';
import { importData } from 'react-service';
import App from './App.js';

// Restore service data
importData(window.__SERVICE_DATA__);

render(<App post={1} />, document.getElementById('app'));

server.js

import 'isomorphic-unfetch';
import React from 'react';
import { renderToString } from 'react-dom/server';
import Express from 'express';
import { exportData } from 'react-service';
import App from './App.js';

const PORT = process.env.NODE_PORT || 9090;

const app = Express();

app.get('*', async (req, res) => {
  try {
    const app = (<App post={1} />);
    const data = await fetchServices(app);
    const content = renderToString(app);
    const html = `<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<div id="app">${content}</div>
<!-- Transfer data -->
<script>window.__SERVICE_DATA__ = ${exportData(data)}</script>
</body>
</html>
`;
    res.status(200).send(html);
  } catch (e) {
    console.error(e.stack);
    res.status(500).json(e.message);
  }
});

app.listen(PORT, () => {
  console.log(`Server started http://localhost:${PORT}`);
});

License

The MIT License Copyright (c) 2017-2018 Ivan Zakharchenko

5.0.0

6 years ago

4.2.0

6 years ago

4.1.0

6 years ago

4.0.0

6 years ago

3.1.0

6 years ago

3.0.2

7 years ago

3.0.1

7 years ago

3.0.0

7 years ago

2.0.0

7 years ago

1.0.1

7 years ago

1.0.0

7 years ago

0.2.2

7 years ago

0.2.1

7 years ago

0.2.0

7 years ago

0.1.3

7 years ago

0.1.2

7 years ago

0.1.0

7 years ago