All Projects → moodysalem → react-sync

moodysalem / react-sync

Licence: MIT license
A declarative approach to fetching data via a React higher order component

Programming Languages

javascript
184084 projects - #8 most used programming language

Projects that are alternatives of or similar to react-sync

axios-endpoints
Axios endpoints helps you to create a more concise endpoint mapping with axios.
Stars: ✭ 41 (+127.78%)
Mutual labels:  fetch, ajax
Kkjsbridge
一站式解决 WKWebView 支持离线包,Ajax/Fetch 请求,表单请求和 Cookie 同步的问题 (基于 Ajax Hook,Fetch Hook 和 Cookie Hook)
Stars: ✭ 462 (+2466.67%)
Mutual labels:  fetch, ajax
electron-request
Zero-dependency, Lightweight HTTP request client for Electron or Node.js
Stars: ✭ 45 (+150%)
Mutual labels:  fetch, ajax
Thwack
A tiny modern data fetching solution
Stars: ✭ 268 (+1388.89%)
Mutual labels:  fetch, ajax
Wretch Middlewares
Collection of middlewares for the Wretch library. 🎁
Stars: ✭ 42 (+133.33%)
Mutual labels:  fetch, ajax
vue-methods-promise
Let Vue methods support return Promise
Stars: ✭ 35 (+94.44%)
Mutual labels:  fetch, ajax
Redux Requests
Declarative AJAX requests and automatic network state management for single-page applications
Stars: ✭ 330 (+1733.33%)
Mutual labels:  fetch, ajax
better-mock
Forked from Mockjs, Generate random data & Intercept ajax request. Support miniprogram.
Stars: ✭ 140 (+677.78%)
Mutual labels:  fetch, ajax
React Native Background Task
Periodic background tasks for React Native apps, cross-platform (iOS and Android), which run even when the app is closed.
Stars: ✭ 873 (+4750%)
Mutual labels:  fetch, sync
Xhr.js
🌎 xhr.js is a library(< 2Kb) to make AJAX/HTTP requests with XMLHttpRequest.
Stars: ✭ 12 (-33.33%)
Mutual labels:  fetch, ajax
Unfetch
🐕 Bare minimum 500b fetch polyfill.
Stars: ✭ 5,239 (+29005.56%)
Mutual labels:  fetch, ajax
Zl Fetch
A library that makes the Fetch API a breeze
Stars: ✭ 186 (+933.33%)
Mutual labels:  fetch, ajax
Fetch Plus
🐕 Fetch+ is a convenient Fetch API replacement with first-class middleware support.
Stars: ✭ 116 (+544.44%)
Mutual labels:  fetch, ajax
Wretch
A tiny wrapper built around fetch with an intuitive syntax. 🍬
Stars: ✭ 2,285 (+12594.44%)
Mutual labels:  fetch, ajax
pianola
A declarative function composition and evaluation engine.
Stars: ✭ 18 (+0%)
Mutual labels:  declarative
react-animation-frame
A React higher-order component that invokes a callback in a wrapped component via requestAnimationFrame
Stars: ✭ 47 (+161.11%)
Mutual labels:  higher-order-component
awesome-fetch
Command-line fetch tools for system/other information
Stars: ✭ 177 (+883.33%)
Mutual labels:  fetch
lightings
A lightweight Ajax Library
Stars: ✭ 20 (+11.11%)
Mutual labels:  ajax
simple-page-ordering
Order your pages and other hierarchical post types with simple drag and drop right from the standard page list.
Stars: ✭ 88 (+388.89%)
Mutual labels:  ajax
miniprogram-network
Redefine the Network API of Wechat MiniProgram (小程序网络库)
Stars: ✭ 93 (+416.67%)
Mutual labels:  fetch

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('/')}/>
);
Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].