Git Product home page Git Product logo

react-sync's Introduction

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

Name Description Type Required Default
url The url to fetch without any query parameters string Yes
headers Object containing all the headers to pass to the request object No null
params Object containing all the query parameters to pass to the request object No null
toQueryString Function used to convert the query parameters prop to a query string function No ./toQueryString.js
toData Function that takes a fetch response object and returns a promise that resolves to the data in the response function No returns response JSON by default
children Function that takes an object {promise, data, error} and returns a node to be rendered function Yes

Source: props.jsx

Child Props

The function passed to the children prop receives the fetch state

Name Description Type
promise The pending promise if any requests are outstanding instanceof Promise
data Data that has been fetched from the API result of toData
error Any fetch errors that may have occurred instanceof 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('/')}/>
);

react-sync's People

Contributors

lsanwick avatar moodysalem avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

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.