Giter Site home page Giter Site logo

harishjangra / redux-fetch-data Goto Github PK

View Code? Open in Web Editor NEW

This project forked from digiaonline/redux-fetch-data

0.0 1.0 0.0 719 KB

Redux utility library for fetching data using promises on both server and client.

Home Page: http://nordsoftware.github.io/redux-fetch-data

License: MIT License

JavaScript 100.00%

redux-fetch-data's Introduction

redux-fetch-data

Build Status Test Coverage Code Climate Scrutinizer Code Quality StyleCI npm version npm downloads License

Redux utility library for fetching data using promises on both server and client.

Install

npm install redux-fetch-data --save

Usage

Initial setup

On the server

Here is an example setup of a simple server. In this example we used Express, but any server framework will do.

import Express from 'express';
import React from 'react';
import { renderToString } from 'react-dom/server';
import { match, RouterContext } from 'react-router';
import { createStore, combineReducers } from 'redux';
import { Provider } from 'react-redux';
import { fetchDataOnServer, reducer as fetching } from 'redux-fetch-data';
import createHistory from 'react-router/lib/createMemoryHistory';

import routes from '../../routes';

const app = Express();

// Renders the actual HTML page
function renderHtml(html, state) {
  return `
    <!doctype html>
    <html>
      <body>
        <div id="root">${html}</div>
        <script dangerouslySetInnerHTML={{__html: `window.__INITIAL_STATE__=${JSON.stringify(state)};`}}
                charSet="UTF-8"/>
      </body>
    </html>
  `;
}

// Register the rendering middleware
app.use((req, res) => {
  const history = createHistory(req.originalUrl);
  const store = createStore(combineReducers({ fetching }));

  match({ routes, location: req.url }, (err, redirect, renderProps) => {
    // Fetch data
    fetchDataOnServer(renderProps, store).then(() => {
      // Data has been fetched, resolve request
      if (err) {
        res.status(500).send(err.message);
      } else if (redirect) {
        res.redirect(redirect.pathname + redirect.search);
      } else if (renderProps) {
        // Render the root component
        const html = renderToString((
          <Provider store={store} key="provider">
            <RouterContext {...renderProps}/>
          </Provider>
        ));

        // Send the rendered page back to the client
        res.status(200).send(renderHtml(html, store.getState()));
      } else {
        res.status(404).send('Not found.');
      }
    });
  });
});

app.listen(3000);

On the client

Here is an example of a client-side entry script.

import React from 'react';
import { createStore, combineReducers } from 'redux';
import { render } from 'react-dom';
import { Router, browserHistory } from 'react-router';
import { Provider } from 'react-redux';
import { FetchData, reducer as fetching } from 'redux-fetch-data';

import routes from './routes';

// Hydrate the initial state from the server state
const initialState = window.__INITIAL_STATE__;
const store = createStore(combineReducers({ fetching }), initialState);

render(
  <Provider store={store} key="provider">
    <Router render={props => <FetchData {...props}/>}
            history={browserHistory}
            routes={routes}/>
  </Provider>,
  document.getElementById('root')
);

Fetching data

Instead of loading data in componentWillMount, move that logic to a static fetchData method. This method should return a promise. Also, make sure you only fetch data from your containers (top-level components), and pass down the data as props to sub-components.

export class Foo extends Component {
  static fetchData() {
    // this method should return a promise
  }
  .....
}

Protip! You can use Promise.all to combine multiple promises into one.

Tests

Run the test suite:

npm test

Run the test suite in watch mode:

npm run test:watch <path>

Generate the code coverage report:

npm run test:cover

License

See LICENSE.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.