Coder Social home page Coder Social logo

fetch-hoc's Introduction

fetch-hoc

Build Status Coverage Status npm version

A React higher order component for fetching data from a server and passing the result as props.

Using a HoC for fetching data is easier to understand and master than redux, while at the same time being more consise than writing utilities and extending components.

The resource can be either a string or a function. If the resouce is a function, then the HoC will automatically re-fetch the resouce when the resource URL changes.

This library is super tiny, measuring just over 1kB gzipped, and has no dependencies!

Installation

yarn add fetch-hoc
# or
npm i -S fetch-hoc

If you don't yet use npm or a bundler like webpack, you can get a UMD bundle from unpkg. Simply add one of the following links into your app, and the library will be accessible as FetchHOC on window. Remember to replace [VERSION] with the version you want.

<script src="https://unpkg.com/fetch-hoc@[VERSION]/dist/fetch-hoc.min.js"></script>

Usage

Now it's my job to tell you why this library is cool.

Simply wrap your component in the result of the fetch function to get started. Using this method enables most of your components to be written as functional stateless components, which is great for legibility and testabiliy.

fetch('/some/static/resource')(Component)
// Or
fetch(props => `/some/resource/${props.someProp}`)(Component)

Here is a more complete example:

const FooComponent = props => {
  if (props.error) {
    return <div className="error">{`An error occured! ${props.error}`}</div>;
  }
  if (props.loading) {
    return <div className="loading">Loading...</div>;
  }

  return (
    <div>
      {props.data.map(row => <div>{row.text}</div>)}
    </div>
  );
}

// This feeds the props used in render
fetch('http://foo.com/bar')(FooComponent);

If you need more flexibility in your component, you can also use a function to reduce the URL from the component's props. These props can be redux props if you also have used connect on the component.

// With props from parent
fetch(props => `/user/${props.user}/cart`)(FooComponent);

// With redux
compose(
  mapStateToProps(state => ({ user: state.user })),
  fetch(props => `/user/${props.user}/cart`),
)(FooComponent);

Example: Composition is king

Use composition to compose behaviors upon the props this HoC provides! For example, to add an easily reusable loading icon and error message:

// withLoadingAnimation.js
export default Component => props => (
  props.loading
    ? <YourLoadingComponent />
    : <Component {...props} />
);
// withErrorMessage.js
export default message => Component => props => (
  props.error
    ? <div className="error">{message}</div>
    : <Component {...props} />
);
// FooComponent.js
import withLoadingAnimation from './withLoadingAnimation';
import withErrorMessage from './withErrorMessage';

const FooComponent = ({ data }) => (
  <div>
    <h1>I will only render on a successfully completed fetch!</h1>
    <pre>{data.toString()}</pre>
  </div>
);

export default compose(
  fetch('/foo'),
  withLoadingAnimation,
  withErrorMessage('Failed to fetch that thing'),
)(FooComponent);

Example: Normalizing data

What about if you need a subset of the data, and the entire dataset is not convenient to work with? Simple, add a HoC for that:

const normalize = func => Component => ({ data, ..rest }) => (
  <Component data={func(data)} {...rest} />
);

export default compose(
  fetch('/foo'),
  normalize(data => data.rows.filter(row => row.enabled))
);

API

// @flow

type Options = {
  /* The same as the Fetch API options, see
   * https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch
   */
};

fetch(url: string|Function, options: Options|(props: {}) => Options)(component: React.Component)

The HoC will inject the following props:

Prop Type Description
data Object The data returned from the server
error Error Any error that occured while fetching the data
loading boolean Whether the request is currently in flight
success boolean Whether the request was successfully fetched
response Response The full response with headers. Cloned and can be read again
refetchData Function Forces the component to refetch the data without changing the url

fetch-hoc's People

Contributors

danielr18 avatar eliihen avatar fc avatar joeydebreuk avatar maxsvargal avatar

Stargazers

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

Watchers

 avatar  avatar

fetch-hoc's Issues

Update to 0.2 breaks

After updating to 0.2, none of my requests are fired anymore, loading prop is always false and data always undefined.

Refetch on same url

Is there any way to re fetch even if the url hasn't changed? An example of why this would be useful would be if the data stored at an endpoint changed from a user interaction, and the hoc needs to refresh its contents without completely wanting to reload the page. Considering forking off this repository to attempt to add a flag for this so the componentWillUpdate does not ignore it, but was wondering if you had any suggestions. Thanks!

How to pass authorization headers via props

Hi, I am wondering, since options is an object, how to add authorization headers, coming from props?

My use case:
I am writing an electron app, storing api keys to a redux store. Since the store is available through props, how can I pass props data to fetch-hoc's options?

RFC: Caching of results

Two components on the same page should not need to send two REST requests to fetch the same data. They should be able to share each others' data. This could be a nice performance boost in some cases.

This could also enable fetch-hoc to be a drop in replacement of redux, where you could have a fetchUser fetchHOC in many components around your app.

This can be solved with a cache module, which handles which URLs are currently being fetched.

To dodge some cache confusion, I feel it should clear the cache on unmount if no other components rely on this data so that next time a component mounts with this URL, it re-fetches it. This could be done by keeping track of how many components currently subscribe to the cache entry, and clearing it when it becomes 0.

An example of how this cache could look:

const cache = {
  'https://google.com': {
    subscribers: 2,
    data: (received data),
    fetching: true,
    awaitCompletion: Promise,
  },
};

And the corresponding FetchHOC code might look something like this:

const cacheEntry = cache[url];

if (cacheEntry && cacheEntry.fetching) {
  ++cacheEntry.subscribers;
  await cacheEntry.awaitCompletion();
  this.setState(/* data from cacheEntry */);
} else {
  cache[url] = {
    data: null,
    fetching: true, 
    subscribers: 1,
    awaitCompletion: new Promise(...),
  };
  // fetch as normal
}

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.