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-backend

v1.1.2

Published

A framework which help fetch data from backends and provide them to React.js components.

Downloads

7

Readme

react-backend

A framework which help fetch data from backends and provide them to React components.

Motivations

React.js doesn't provide any core feature to interface with a database back-end nor with a REST API. At Hextrakt, we wanted a simple (and beautiful) solution, and didn't want to learn a new language such as GraphQL/Relay.
Redux provides the frame to manage UI state, and respond to user actions, but doesn't help on the server side, where initial state is immutable.
So we built this framework to :

  • be able to render a complete DOM tree at the server side
  • be able to specify which data are needed at each application path
  • write code in a declarative way, in a "react-like" way, leveraging React Router API v4
  • provide data at the server side as well as at the client side
  • provide preloaded data (in a javascript variable) to initialize client side components

Requirements

There is no specific requirement to use this framework. It is written in ES6, but the package is translated using Babel into plain javascript so that everybody might "require" it. You just need to use React Router API v4.

Installation

To use the framework

yarn add react-backend 

or

npm install react-backend

To test it, first clone the Git repository of react-backend. Then, run

yarn install
yarn build
yarn test

To run the samples, do the three steps above, then

cd src/samples
yarn install
yarn build-samples
yarn start-samples

and navigate to http://localhost:3000

Features and usage

Use the NeedsData component to declare the application data needs. Example 1. Tell that getUserInfo is needed when navigating to /user :

<Route path='/user' render={() => (
  <NeedsData needs="getUserInfo"/>
  )}/>
</Route>

Data needs are additive. Example 2. Tell that both "getUserInfo" and "getUserProfile" are needed when navigating to /user/profile:

<Route path='/user' render={() => (
  <NeedsData needs="getUserInfo">
)}/>
<Route path='/user/profile' render={() => (
  <NeedsData needs="getUserProfile"/>
)}/>

Data needs can be nested. Example 3. This is the same as example 2, but written in a nested way:

<Route path='/user' render={() => (
  <NeedsData needs="getUserInfo">
    <Route path='/user/profile' render={() => (
      <NeedsData needs="getUserProfile"/>
    )}/>
  </NeedsData>
  )}/>
</Route>

Write a DataProvider class to resolve the needs into Promise objects. Your DataProvider might fetch data from the session, from the database, or from REST services.

class MyDataProvider extends DataProvider {
  getUserInfo() {
    return database.loadUserInfo(userId) // should return a Promise
  }
  getUserProfile() {
    return database.loadUserProfile(userId) // should return a Promise
  }
}

You can have a different DataProvider at the server side (to load data from database) and at the client side (to load data from REST services).

You can declare dependencies between your data using the DataProvider.when() function. For instance, if getUserInfo needs the session user id, you can write this in your DataProvider class:

getUserInfo() {
  return when("getUserId").then(id => database.loadUserInfo(id))
}
getUserId() {
  return Promise.resolve(session.getCurrentUserId()) // depending on your session implementation
}

Needs are resolved once and cached. If several needs share the same base need, the shared need will be loaded only one time. Use the DataProvider.invalidate(someNeed) function to tell the dataprovider that someNeed should be reloaded at the next UI refresh.

Wrap all your data needs with a ProviderRules component, and give it the dataProvider instance:

<ProviderRules dataProvider={myDataProvider}>
  <Route path='/user' render={() => (
    <NeedsData needs="getUserInfo"/>
  )}/>
</ProviderRules>

The ProviderRules component will be responsible to collect all the data needs which are declared in its subtree.

Place all your presentational components within a WithData component. This will have two benefits:

  • First, your presentation will not be rendered until the data needs are resolved
  • Secondly, you can access the dataProvider instance, either from the React context or from the dataProvider prop when using the withDataProvider HOC.

Use either DataProvider.getData(), DataProvider.getError(), DataProvider.hasErrors() within your presentational componenents to access the resolved data or errors.

<WithData dataProvider={dataProvider}>
  <UserForm/>
</WithData>
class _UserForm extends React.Component {
  render() {
    const {dataProvider} = this.props
    if (!dataProvider.hasErrors()) {
      const userInfo = dataProvider.getData("getUserInfo")
      // add here your rendering logic
    }
    else if (dataProvider.getError("getUserInfo")) {
      // show specific error
    }
  }
}
const UserForm = withDataProvider(_UserForm)

In order to render the complete DOM tree at the server side, you can use the ServerRenderer class, this way:

const context = {}
const myDataProvider = new MyDataProvider()

new ServerRenderer(myDataProvider, 
  (<StaticRouter location={ req.url } context={ context }>
    <Fragment>
      <ProviderRules dataProvider={myDataProvider}>
        <DataNeeds/>
      </ProviderRules>
      <WithData dataProvider={myDataProvider}>
        <App/>
      </WithData>  
    </Fragment>
  </StaticRouter>)
)
.render()
.then(markup => {
  let data = myDataProvider.values
  res.status(200).send(Template({data, markup}))
})
.catch (function (error) {
  console.log("There was a problem : ", error)
})

The Template function can look like this (a bit simplified):

export default ({ data, markup }) => {
    return `<!doctype html>
    <html>
    <head>
      <script>var data = ${JSON.stringify(data)}</script>
    </head>
    <body>
      <div id="root">${markup}</div>
      <script src="/js/client.js" async></script>
    </body>
    </html>`
}

Samples

You can find all the sample code in the samples directory of react-backend.