0.2.0 • Published 7 years ago
react-fetchsome v0.2.0
Introduction
react-fetchsome is a react library that abstracts aways data fetching using fetch API.
Is it for me?
- you don't want to write loading states all over again
- you don't want to be rethinking over and over how to work with fetch APIin best way
- you want consistent approach to data fetching in your whole application
- you don't need server-rendering
Install
Add it to your project with npm:
npm install --save react-fetchsomeor yarn:
yarn add react-fetchsomeRequirements
The package expects at least react@16.0.0.
Since it depends on Fetch API it must run in browsers supporting this API or you must include a polyfill.
Features
key:
- mature resource states (loading, refetching, errors, ...)
- consistent error handling
- guided usage of fetch enforcing best practices
advanced:
- loading multiple resources
tech:
- flow typed
Basic Example
function CreatePostForm(props) {
  return (
    <div>
      New post
      <div>
        title: <input ref={titleRef} />
      </div>
      <button
        disabled={props.isLoading}
        onClick={() => {
          const title = titleRef.current && titleRef.current.value;
          props.initFetch({ title });
        }}
      >
        Create posta
      </button>
      <div>{props.isLoading ? '...' : ''}</div>
    </div>
  );
}
const resources = {
  createPost: {
    url: "https://jsonplaceholder.typicode.com/posts",
    method: "POST"
  }
};
function Example() {
  return (
    <FetchData
      env={env}
      resources={resources}
      render={(resources, meta) => {
        const { createPost } = resources;
        if (createPost.hasLoaded()) {
          return (
            <div>
              <div>Created post</div>
              <div>{JSON.stringify(createPost.data)}</div>
            </div>
          );
        }
        return (
          <CreatePostForm
            isLoading={createPost.isLoading()}
            initFetch={createPost.initFetch}
          />
        );
      }}
    />;
  )
}Documentation
TODO.
Limitations
- no server-rendering support
Other solutions
Alternatives:
Inspired by: