# @harishjangra/redux-fetch-data

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

Latest version **0.1.6** (published 2020-03-06) · MIT license · 0 weekly downloads

## Install

```sh
npm install @harishjangra/redux-fetch-data
pnpm add @harishjangra/redux-fetch-data
yarn add @harishjangra/redux-fetch-data
bun add @harishjangra/redux-fetch-data
```

## Health

**Score 15/100 (F)** — status: abandoned.

Positive: no vulnerabilities.

Warnings: low downloads; no types; no esm support; pre 1.0.

Negative: abandoned; low maintenance score.

## Facts

| | |
|---|---|
| Version | 0.1.6 |
| Published | 2020-03-06 |
| First published | 2020-03-06 |
| Weekly downloads | 0 |
| License | MIT |
| TypeScript types | none |
| Module format | CommonJS |
| Dependencies | 3 |
| Unpacked size | 19.4 KB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| GitHub stars | 40 |
| Author | Harish Jangra |
| Maintainers | harishjangra |
| Keywords | redux, ssr, promise, async, data, react-component |

## Links

- npm: https://www.npmjs.com/package/@harishjangra/redux-fetch-data
- Repository: https://github.com/nordsoftware/redux-fetch-data
- Homepage: https://github.com/harishjangra/redux-fetch-data#readme
- Issues: https://github.com/nordsoftware/redux-fetch-data/issues
- npm.io page: https://npm.io/package/@harishjangra/redux-fetch-data

## Dependencies (3)

- [prop-types](https://npm.io/package/prop-types.md) ^15.7.2
- [npm-run-all](https://npm.io/package/npm-run-all.md) ^4.0.1
- [redux-actions](https://npm.io/package/redux-actions.md) ^0.9.1

## Alternatives

- [promise-throttle](https://npm.io/package/promise-throttle.md) — 44.2K weekly downloads
- [@commercetools/sync-actions](https://npm.io/package/@commercetools/sync-actions.md) — 25.1K weekly downloads
- [cwait](https://npm.io/package/cwait.md) — 21.4K weekly downloads
- [@ledgerhq/hw-app-cosmos](https://npm.io/package/@ledgerhq/hw-app-cosmos.md) — 4.2K weekly downloads
- [@financial-times/o-loading](https://npm.io/package/@financial-times/o-loading.md) — 2.8K weekly downloads

## Recent versions

- 0.1.6 (latest) — 2020-03-06
- 0.1.5 — 2020-03-06

## README

# redux-fetch-data

[![Build Status](https://travis-ci.org/digiaonline/redux-fetch-data.svg?branch=master)](https://travis-ci.org/digiaonline/redux-fetch-data)
[![Test Coverage](https://codeclimate.com/github/digiaonline/redux-fetch-data/badges/coverage.svg)](https://codeclimate.com/github/digiaonline/redux-fetch-data/coverage)
[![Code Climate](https://codeclimate.com/github/digiaonline/redux-fetch-data/badges/gpa.svg)](https://codeclimate.com/github/digiaonline/redux-fetch-data)
[![Scrutinizer Code Quality](https://scrutinizer-ci.com/g/digiaonline/redux-fetch-data/badges/quality-score.png?b=master)](https://scrutinizer-ci.com/g/digiaonline/redux-fetch-data/?branch=master)
[![StyleCI](https://styleci.io/repos/58546352/shield?style=flat)](https://styleci.io/repos/58546352)
[![npm version](https://img.shields.io/npm/v/redux-fetch-data.svg)](https://www.npmjs.com/package/redux-fetch-data)
[![npm downloads](https://img.shields.io/npm/dt/redux-fetch-data.svg)](https://www.npmjs.com/package/redux-fetch-data)
[![License](https://img.shields.io/badge/license-MIT-blue.svg)](https://raw.githubusercontent.com/digiaonline/redux-fetch-data/master/LICENSE)

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

## Install

```bash
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.

```js
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.

```js
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.

```js
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:

```bash
npm test
```

Run the test suite in watch mode:

```bash
npm run test:watch <path>
```

Generate the code coverage report:

```bash
npm run test:cover
```

## License

See [LICENSE](LICENSE).

---
_Source: https://npm.io/package/@harishjangra/redux-fetch-data · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
