0.9.0 • Published 7 years ago

react-sync v0.9.0

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

Build Status npm version react-sync

A declarative approach to fetching API data using HTML5 Fetch

Purpose

react-sync provides a single higher order component used for fetching data from your APIs

Rendering the data is your responsibility, but refreshing the data from the API is as simple as changing the parameters of your request. Let the component manage the state of fetching the data.

ReactSync Props

NameDescriptionTypeRequiredDefault
urlThe url to fetch without any query parametersstringYes
headersObject containing all the headers to pass to the requestobjectNonull
paramsObject containing all the query parameters to pass to the requestobjectNonull
toQueryStringFunction used to convert the query parameters prop to a query stringfunctionNo./toQueryString.js
toDataFunction that takes a fetch response object and returns a promise that resolves to the data in the responsefunctionNoreturns response JSON by default
childrenFunction that takes an object {promise, data, error} and returns a node to be renderedfunctionYes

Source: props.jsx

Child Props

The function passed to the children prop receives the fetch state

NameDescriptionType
promiseThe pending promise if any requests are outstandinginstanceof Promise
dataData that has been fetched from the APIresult of toData
errorAny fetch errors that may have occurredinstanceof Error

Install

npm install --save react-sync

Alternately this project builds to a UMD module named ReactSync, so you can include a unpkg script tag in your page

Look for window.ReactSync when importing the UMD module via a script tag

Usage

See the demo source for example usage with filtering

import React from 'react';
import ReactSync from 'react-sync';

const StarGazers = ({ owner, repo, githubToken }) => (
  <ReactSync 
    url={`https://api.github.com/repos/${owner}/${repo}/stargazers`} 
    headers={{Authorization: `token ${githubToken}`}}>
    {
      ({ promise, data, error }) => (
        <span>
          {promise !== null ? 'Loading...' : data}      
        </span>
      )
    }
  </ReactSync>
);

Patterns

Composition is king when using this component.

For example, want to automatically refetch every minute? Create a component that wraps ReactSync and updates a timestamp query parameter every minute.

import React, { Component } from 'react';
import PropTypes from 'prop-types';
import Sync from 'react-sync';

const now = () => (new Date()).getTime();

export default class RefreshSync extends Component {
  static propTypes = {
    refreshEvery: PropTypes.number
  };

  _timer = null;
  state = {
    _ts: now()
  };

  triggerNextRefresh = after => {
    clearTimeout(this._timer);
    this._timer = setTimeout(this.refresh, after);
  };

  refresh = () => {
    this.setState({ _ts: now() });
    this.triggerNextRefresh(this.props.refreshEvery);
  };

  componentDidMount() {
    this.triggerNextRefresh(this.props.refreshEvery);
  }

  componentWillReceiveProps({ refreshEvery }) {
    if (refreshEvery !== this.props.refreshEvery) {
      this.triggerNextRefresh(refreshEvery);
    }
  }

  render() {
    const { params, ...rest } = this.props,
      { _ts } = this.state;

    return <Sync {...rest} params={{ ...params, _ts }}/>;
  }
}

What about attaching a token from the context to all requests?

import React, { Component } from 'react';
import PropTypes from 'prop-types';
import Sync from 'react-sync';

export default class AuthenticatedSync extends Component {
  static contextTypes = {
    token: PropTypes.string
  };

  render() {
    const { headers, ...rest } = this.props,
      { token } = this.context;

    return (
      <Sync
        {...rest}
        headers={{
          ...headers,
          Authorization: token ? `Bearer ${token}` : null
        }}
      />
    );
  }
}

How about just defaulting a base URL?

import React from 'react';
import Sync from 'react-sync';

export const MyApiSync = ({ path, ...rest }) => (
  <Sync {...rest} url={[ 'https://my-api.com', path ].join('/')}/>
);
0.9.0

7 years ago

0.8.1

7 years ago

0.8.0

7 years ago

0.6.4

7 years ago

0.6.3

7 years ago

0.6.2

7 years ago

0.6.1

7 years ago

0.5.4

8 years ago

0.5.3

8 years ago

0.5.2

8 years ago

0.5.1

8 years ago

0.5.0

8 years ago

0.4.2

8 years ago

0.4.1

8 years ago

0.4.0

8 years ago

0.3.0

8 years ago

0.2.0

8 years ago

0.1.4

8 years ago

0.1.2

8 years ago

0.1.1

8 years ago

0.1.0

8 years ago