All Projects → techniq → React Fetch Component

techniq / React Fetch Component

Licence: mit
React component to declaratively fetch data

Programming Languages

javascript
184084 projects - #8 most used programming language

Projects that are alternatives of or similar to React Fetch Component

Mfetch
mfetch will provide you with a strong ability to request resource management
Stars: ✭ 90 (-41.18%)
Mutual labels:  fetch
Electron Vue Cloud Music
🚀Electron + Vue 仿网易云音乐windows客户端
Stars: ✭ 1,894 (+1137.91%)
Mutual labels:  fetch
Tipple
A lightweight dependency-free library for fetching data over REST with React.
Stars: ✭ 133 (-13.07%)
Mutual labels:  fetch
Php Fetch
A simple, type-safe, zero dependency port of the javascript fetch WebApi for PHP
Stars: ✭ 95 (-37.91%)
Mutual labels:  fetch
Hyperapp Fx
Effects for use with Hyperapp
Stars: ✭ 105 (-31.37%)
Mutual labels:  fetch
Nion
🌵 Declarative API Data Management Library built on top of redux 🌵
Stars: ✭ 116 (-24.18%)
Mutual labels:  fetch
React Ufo
🛸 react-ufo - A simple React hook to help you with data fetching 🛸
Stars: ✭ 85 (-44.44%)
Mutual labels:  fetch
React Infinite Scroll Hook
A simple hook to create infinite scroll list components
Stars: ✭ 151 (-1.31%)
Mutual labels:  fetch
Jmusic
重构一款音乐app
Stars: ✭ 108 (-29.41%)
Mutual labels:  fetch
Nuxt Dev To Clone
Build DEV.TO clone with Nuxt.js and new `fetch` hook
Stars: ✭ 118 (-22.88%)
Mutual labels:  fetch
Redux Cnode
react+react-router+redux+es6+antd-mobile+webpack版本的Cnode
Stars: ✭ 96 (-37.25%)
Mutual labels:  fetch
Superlifter
A DataLoader for Clojure/script
Stars: ✭ 102 (-33.33%)
Mutual labels:  fetch
Fetch Plus
🐕 Fetch+ is a convenient Fetch API replacement with first-class middleware support.
Stars: ✭ 116 (-24.18%)
Mutual labels:  fetch
Apipeline
Feature-rich and pluggable offline-first API wrapper for all your javascript environements ! Easily wire-up your API and make your app work offline in minutes.
Stars: ✭ 92 (-39.87%)
Mutual labels:  fetch
Fetch
Fetch Standard
Stars: ✭ 1,794 (+1072.55%)
Mutual labels:  fetch
Fetcher Ts
Type-safe wrapper around Fetch API
Stars: ✭ 87 (-43.14%)
Mutual labels:  fetch
Vue2 Element
基于vue2 + vue-router2 + element-ui + vuex2 + fetch + webpack2 企业级后台管理系统最佳实践
Stars: ✭ 112 (-26.8%)
Mutual labels:  fetch
Holen
Declarative fetch for React
Stars: ✭ 152 (-0.65%)
Mutual labels:  fetch
Use Http
🐶 React hook for making isomorphic http requests
Stars: ✭ 2,066 (+1250.33%)
Mutual labels:  fetch
Vue Spa Project
vue.js + vuex + vue-router + fetch + element-ui + es6 + webpack + mock 纯前端SPA项目开发实践
Stars: ✭ 118 (-22.88%)
Mutual labels:  fetch

react-fetch-component CircleCI

React component to declaratively fetch data

Install

yarn add react-fetch-component

or

npm install --save react-fetch-component

Usage

You supply a single function as a child of <Fetch /> which receives a single argument as an object. The function will be called anytime the state of the fetch request changes (for example, before a request has been made, while the request is in flight, and after the request returned a response).

While you can pass a single property to the function (for example, (fetchProps) => ...), it is common to instead use object destructuring to peel off the properties on the object you plan to use.

An example of destructing and using the most common properties loading, error, and data.

<Fetch url="someUrl">
  {({ loading, error, data }) => (
    <div>
      {loading &&
        {
          /* handle loading here */
        }}
      {error &&
        {
          /* handle error here */
        }}
      {data &&
        {
          /* handle data here */
        }}
    </div>
  )}
</Fetch>

You can also use React's context via <Fetch.Consumer> for accessing the state in a deep tree (or to create components based on state)

const Loading = () => <Fetch.Consumer>{({ loading }) => loading ? <MySpinner /> : null}</Fetch.Consumer>
const Error = () => <Fetch.Consumer>{({ error }) => error ? <MyError error={error} /> : null}</Fetch.Consumer>

<Fetch url="someUrl">
  <div>
    <div>
      <div>
        <Loading />
        <Error />
        <Fetch.Consumer>
          {({ data }) => <div>{ data ? /* handle data here */ : null}</div>}
        </Fetch.Consumer>
      </div>
    </div>
  </div>
</Fetch>

Props

  • url (string) - address of the request. Initial fetch will only be created when it's a non-empty string. You can initially set this to undefined, false, or an empty string to delay the fetch to a later render.
  • options (object|function) - request options such as method, headers, credentials, etc. If passed as a function, it will not be evaluated until the request is sent, which is useful when calling expensive methods like JSON.stringify for options.body for example.
  • as - declare how to handle the response body
    • default: auto (will attempt to parse body based on Content-Type header)
    • can either be a string for any of the body methods including:
      • arrayBuffer
      • blob
      • formData
      • json
      • text
    • or a function that takes in the response and returns a Promise. For example <Fetch as={res => res.text()} />
    • or an object that maps the Content-Type of the response to a function that takes in the response and returns a Promise. For example <Fetch as={{ 'application/json': res => JSON.parse(res.text(), customReviver)}} />. html, json, xml, and other are also available for simplification.
  • cache (boolean|object)
    • If set, will cache responses by url and return values from cache for matches urls without issues another request. Useful for typeahead features, etc.
    • If true, will use an instance of SimpleCache per component instance
    • Can supply an instance with get(url) and set(url, promise) methods. Passing an instance of SimpleCache allows for multiple instances to share the same (simple) cache
    • Other implementations of a cache can be supplied for more control (LRU, persist to local/sessionStorage, etc)
    • default: false
  • manual (boolean) - If true, requires calling fetch explicitly to initiate requests. Useful for better control of POST/PUT/PATCH requests.
    • default: false
  • onDataChange (function) - Function called only when data is changed. It is called before onChange, and if a result is returned (i.e. not undefined), this value will be used as data passed to onChange and the child function instead of the original data. onDataChange also receives the current data as the second parameter, which allows for concatenating data (ex. infinity scroll).
  • onChange (function) - Function called with same props as child function. Useful to call setState (or dispatch a redux action) since this is not allowed within render. onChange will always be called even if <Fetch /> component has been unmounted.
    • default: undefined
  • fetchFunction (function) - Specify own fetch function. Useful to debounce fetch requests (although probably best to debounce outside of <Fetch /> so not call unneccessary renders)
    • default: window.fetch

Object properties passed to child function

  • loading

    • Set to true while request is in flight
    • Set to false once response has returned
    • Set to null when manual={true} before fetch() is called
  • error

    • Is undefined while request is pending
    • Will be set to the parsed response body (json by default) if !response.ok (i.e. status < 200 || status >= 300)
    • Will be set to an Error instance if thrown during the request (ex. CORS issue) or if thrown while attemping to parse the response body, such as returning text/html when json was expected (which is the default parser)
    • Will remain undefined if neither of the previous occur
  • data

    • Is undefined while request is pending
    • Set to parsed response body (json by default) unless one of the error conditions occur
  • request

    • Set to an object containing the props passed to the component (url, options, etc) when request is sent.
    • Added for convenience when <Fetch /> is wrapped by your own data component (ex. <UserData />)
  • response

    • Set to the response of the fetch call
    • Useful to check the status code/text, headers, etc
  • fetch

    • Function that can be called to create a new fetch request (useful when last request had an error or you want to manually refresh the data (see manual prop))
    • The first 2 parameters match window.fetch (url, options). A third parameter (updateOptions) is available to pass options to the update phase (where onChange, onDataChange, and the child render function is called). Currently only 1 option is available (ignorePreviousData) which passes undefined as the current data (second parameter) to onDataChange, which is useful when using onDataChange to concatenate data across requests (ie. infinite loading) and the query changes
  • clearData

    • Function to clear data state.

Examples

Include credentials

<Fetch url="someUrl" options={{ credentials: 'include' }}>
  {/* ... */}
</Fetch>

More interactive examples on CodeSandbox

See also

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].