This package has been deprecated

Author message:

WARNING: This project has been renamed. Install react-universal-data instead.

react-get-app-data

1.1.1 • Public • Published

🗂 react-get-app-data

Simple React HOC for getting intial and subsequent async data + SSR

Install

$ yarn add react-get-app-data

API

Example

As HOC

import 'isomorphic-fetch'
import React from 'react'
import ReactDOM from 'react-dom'
import { withData } from 'react-get-app-data'
 
const Page = ({ user = {} }) => <div>Hello {user.name}!</div>
 
const PageWithData = withData(() =>
  fetch('https://jsonplaceholder.typicode.com/users/1')
    .then(res => res.json())
    .then(user => ({ user }))
)(Page)
 
ReactDOM.render(<PageWithData />, document.getElementById('root'))

Edit pp98jzr4y7


Or as static property inside component

import 'isomorphic-fetch'
import React from 'react'
import ReactDOM from 'react-dom'
import { withData } from 'react-get-app-data'
 
class Page extends React.Component {
  static defaultProps = {
    user: {}
  }
  static async getData() {
    const user = await fetch(
      'https://jsonplaceholder.typicode.com/users/1'
    ).then(res => res.json())
 
    return {
      user
    }
  }
  render() {
    const { user } = this.props
 
    return <div>Hello {user.name}!</div>
  }
}
 
const PageWithData = withData()(Page)
 
ReactDOM.render(<PageWithData />, document.getElementById('root'))

Edit ovxkz1ojj9

Server-Side Rendering

With two-step rendering on server

// server.js
 
import React from 'react'
import { renderToString } from 'react-dom/server'
import { getAppInitialData } from 'react-get-app-data'
import { html } from 'common-tags'
import App from './app'
 
export default () => (req, res) => {
  const appElement = (<App />)
 
  getAppInitialData(appElement)
    .then((initialData) => {
      const app = renderToString(appElement)
 
      res.send(html`
        <!DOCTYPE html>
        <html>
          <body>
            <div id="app">${app}</div>
            <script>
              (function () {
                window._ssr = ${JSON.stringify({ initialData })};
              })();
            </script> 
            <script src="/client.js"></script> 
          </body>
        </html>
      `)
    })
    .catch((error) => {
      console.error(error)
      res.status(500)
      res.send(`Error: ${error.message}`)
    })
}

Hydrate app and initialData in client

// client.js
 
import React from 'react'
import ReactDOM from 'react-dom'
import { hydrateData } from 'react-get-app-data'
import App from './app'
 
// Get server state
const { initialData } = (window._ssr || {})
 
// Restore app state
hydrateData(initialData)
 
// Render app
ReactDOM.hydrate((
  <App />
), document.getElementById('app'))

Related


MIT © John Grishin

Readme

Keywords

none

Package Sidebar

Install

npm i react-get-app-data

Weekly Downloads

1

Version

1.1.1

License

MIT

Unpacked Size

33.7 kB

Total Files

21

Last publish

Collaborators

  • exah