Git Product home page Git Product logo

react-refetch's Introduction

React Refetch

A simple, declarative, and composable way to fetch data for React components.

React Refetch Logo

Installation

build status npm version npm downloads

Requires React 0.14 or later.

npm install --save react-refetch

This assumes that you’re using npm package manager with a module bundler like Webpack or Browserify to consume CommonJS modules.

The following ES6 functions are required:

Check the compatibility tables (Object.assign, Promise, fetch, Array.prototype.find) to make sure all browsers and platforms you need to support have these, and include polyfills as necessary.

Introduction

See Introducing React Refetch on the Heroku Engineering Blog for background and a quick introduction to this project.

Motivation

This project was inspired by (and forked from) React Redux. Redux/Flux is a wonderful library/pattern for applications that need to maintain complicated client-side state; however, if your application is mostly fetching and rendering read-only data from a server, it can over-complicate the architecture to fetch data in actions, reduce it into the store, only to select it back out again. The other approach of fetching data inside the component and dumping it in local state is also messy and makes components smarter and more mutable than they need to be. This module allows you to wrap a component in a connect() decorator like react-redux, but instead of mapping state to props, this lets you map props to URLs to props. This lets you keep your components completely stateless, describe data sources in a declarative manner, and delegate the complexities of data fetching to this module. Advanced options are also supported to lazy load data, poll for new data, and post data to the server.

Example

If you have a component called Profile that has a userId prop, you can wrap it in connect() to map userId to one or more requests and assign them to new props called userFetch and likesFetch:

import React, { Component } from 'react'
import { connect, PromiseState } from 'react-refetch'

class Profile extends Component {
  render() {
    // see below
  }
}

export default connect(props => ({
  userFetch: `/users/${props.userId}`,
  likesFetch: `/users/${props.userId}/likes`
}))(Profile)

When the component mounts, the requests will be calculated, fetched, and the result will be passed into the component as the props specified. The result is represented as a PromiseState, which is a synchronous representation of the fetch Promise. It will either be pending, fulfilled, or rejected. This makes it simple to reason about the fetch state at the point in time the component is rendered:

render() {
  const { userFetch, likesFetch } = this.props

  if (userFetch.pending) {
    return <LoadingAnimation/>
  } else if (userFetch.rejected) {
    return <Error error={userFetch.reason}/>
  } else if (userFetch.fulfilled) {
    return <User user={userFetch.value}/>
  }

  // similar for `likesFetch`
}

See the composing responses to see how to handle userFetch and likesFetch together. Although not included in this library because of application-specific defaults, see an example PromiseStateContainer and its example usage for a way to abstract and simplify the rendering of PromiseStates.

Refetching

When new props are received, the requests are re-calculated, and if they changed, the data is refetched and passed into the component as new PromiseStates. Using something like React Router to derive the props from the URL in the browser, the application can control state changes just by changing the URL. When the URL changes, the props change, which recalculates the requests, new data is fetched, and it is reinjected into the components:

react-refetch-flow

By default, the requests are compared using their URL, headers, and body; however, if you want to use a custom value for the comparison, set the comparison attribute on the request. This can be helpful when the request should or should not be refetched in response to a prop change that is not in the request itself. A common situation where this occurs is when two different requests should be refetched together even though one of the requests does not actually include the prop. Note, this is using the request object syntax for userStatsFetch instead of just a plain URL string. This syntax allows for more advanced options. See the API documentation for details:

connect(props => ({
  usersFetch:  `/users?status=${props.status}&page=${props.page}`,
  userStatsFetch: { url: `/users/stats`, comparison: `${props.status}:${props.page}` }
}))(UsersList)

In this example, usersFetch is refetched every time props.status or props.page changes because the URL is changed. However, userStatsFetch does not contain these props in its URL, so would not normally be refetched, but because we added comparison: ${props.status}:${props.page}, it will be refetched along with usersFetch. In general, you should only rely on changes to the requests themselves to control when data is refetched, but this technique can be helpful when finer-grained control is needed.

If you always want data to be refetched when any new props are received, set the force: true option on the request. This will take precedence over any custom comparison and the default request comparison. For example:

connect(props => ({
  usersFetch: `/users?status=${props.status}&page=${props.page}`,
  userStatsFetch: { url: `/users/stats`, force: true }
}))(UsersList)

Setting force: true should be avoided if at all possible because it could result in extraneous data fetching and rendering of the component. Try to use the default comparison or custom comparison option instead.

Automatic Refreshing

If the refreshInterval option is provided along with a URL, the data will be refreshed that many milliseconds after the last successful response. If a request was ever rejected, it will not be refreshed or otherwise retried. In this example, likesFetch will be refreshed every minute. Note, this is using the request object syntax for likeFetch instead of just a plain URL string. This syntax allows for more advanced options. See the API documentation for details.

connect(props => ({
  userFetch:`/users/${props.userId}`,
  likesFetch: { url: `/users/${props.userId}/likes`, refreshInterval: 60000 }
}))(Profile)

When refreshing, the PromiseState will be the same as the previous fulfilled state, but with the refreshing attribute set. That is, pending will remain unset and the existing value will be left intact. When the refresh completes, refreshing will be unset and the value will be updated with the latest data. If the refresh is rejected, the PromiseState will move into a rejected and not attempt to refresh again.

Fetch Functions

Instead of mapping the props directly to a URL string or request object, you can also map the props to a function that returns a URL string or request object. When the component receives props, instead of the data being fetched immediately and injected as a PromiseState, the function is bound to the props and injected into the component as functional prop to be called later (usually in response to a user action). This can be used to either lazy load data, post data to the server, or refresh data. These are best shown with examples:

Lazy Loading

Here is a simple example of lazy loading the likesFetch with a function:

connect(props => ({
  userFetch: `/users/${props.userId}`,
  lazyFetchLikes: max => ({
    likesFetch: `/users/${props.userId}/likes?max=${max}`
  })
}))(Profile)

In this example, userFetch is fetched normally when the component receives props, but lazyFetchLikes is a function that returns likesFetch, so nothing is fetched immediately. Instead lazyFetchLikes is injected into the component as a function to be called later inside the component:

this.props.lazyFetchLikes(10)

When this function is called, the request is calculated using both the bound props and any passed in arguments, and the likesFetch result is injected into the component normally as a PromiseState.

Posting Data

Functions can also be used for post data to the server in response to a user action. For example:

connect(props => ({
  postLike: subject => ({
    postLikeResponse: {
      url: `/users/${props.userId}/likes`,
      method: 'POST',
      body: JSON.stringify({ subject })
    }
  })
}))(Profile)

The postLike function is injected in as a prop, which can then be tied to a button:

<button onClick={() => this.props.postLike(someSubject)}>Like!</button>

When the user clicks the button, someSubject is posted to the URL and the response is injected as a new postLikeResponse prop as a PromiseState to show progress and feedback to the user.

Manually Refreshing Data

Functions can also be used to manually refresh data by overwriting an existing PromiseState:

connect(props => {
 const url = `/users/${props.userId}`

 return {
   userFetch: url,
   refreshUser: () => ({
     userFetch: {
       url,
       force: true,
       refreshing: true
     }
   })
 }
})(Profile)

The userFetch data is first loaded normally when the component receives props, but the refreshUser function is also injected into the component. When this.props.refreshUser() is called, the request is calculated, and compared with the existing userFetch request. If the request changed (or force: true), the data is refetched and the existing userFetch PromiseState is overwritten. This should generally only be used for user-invoked refreshes; see above for automatically refreshing on an interval.

Note, the example above sets force: true and refreshing: true on the request returned by the refreshUser() function. These attributes are optional, but commonly used with manual refreshes. force: true avoids the default request comparison (e.g. url, method, headers, body) with the existing userFetch request so that every time this.props.refreshUser() is called, a fetch is performed. Because the request would not have changed from the last prop change in the example above, force: true is required in this case for the fetch to occur when this.props.refreshUser() is called. refreshing: true avoids the existing PromiseState from being cleared while fetch is in progress.

Posting + Refreshing Data

The two examples above can be combined to post data to the server and refresh an existing PromiseState. This is a common pattern when responding to a user action to update a resource and reflect that update in the component. For example, if PATCH /users/:user_id responds with the updated user, it can be used to overwrite the existing userFetch when the user updates her name:

connect(props => ({
  userFetch: `/users/${props.userId}`,
  updateUser: (firstName, lastName) => ({
    userFetch: {
      url: `/users/${props.userId}`
      method: 'PATCH'
      body: JSON.stringify({ firstName, lastName })
     }
   })
}))(Profile)

Composing Responses

If a component needs data from more than one URL, the PromiseStates can be combined with PromiseState.all() to be pending until all the PromiseStates have been fulfilled. For example:

render() {
  const { userFetch, likesFetch } = this.props

  // compose multiple PromiseStates together to wait on them as a whole
  const allFetches = PromiseState.all([userFetch, likesFetch])

  // render the different promise states
  if (allFetches.pending) {
    return <LoadingAnimation/>
  } else if (allFetches.rejected) {
    return <Error error={allFetches.reason}/>
  } else if (allFetches.fulfilled) {
    // decompose the PromiseState back into individual
    const [user, likes] = allFetches.value
    return (
      <div>
          <User data={user}/>
          <Likes data={likes}/>
      </div>
    )
  }
}

Similarly, PromiseState.race() can be used to return the first settled PromiseState. Like their asynchronous Promise counterparts, PromiseStates can be chained with then() and catch(); however, the handlers are run immediately to transform the existing state. This can be helpful to handle errors or transform values as part of a composition. For example, to provide a fallback value to likesFetch in the case of failure:

PromiseState.all([userFetch, likesFetch.catch(reason => [])])

Chaining Requests

Inside of connect(), requests can be chained using then(), catch(), andThen() and andCatch() to trigger additional requests after a previous request is fulfilled. These are not to be confused with the similar sounding functions on PromiseState, which are on the response side, are synchronous, and are executed for every change of the PromiseState.

then() is helpful for cases where multiple requests are required to get the data needed by the component and the subsequent request relies on data from the previous request. For example, if you need to make a request to /foos/${name} to look up foo.id and then make a second request to /bar-for-foos-by-id/${foo.id} and return the whole thing as barFetch (the component will not have access to the intermediate foo):

connect(({ name }) => ({
  barFetch: {
    url: `/foos/${name}`,
    then: foo => `/bar-for-foos-by-id/${foo.id}`
  }
}))

andThen() is similar, but is intended for side effect requests where you still need access to the result of the first request and/or need to fanout to multiple requests:

connect(({ name }) => ({
  fooFetch: {
    url: `/foos/${name}`,
    andThen: foo => ({
      barFetch: `/bar-for-foos-by-id/${foo.id}`
    })
  }
}))

This is also helpful for cases where a fetch function is changing data that is in some other fetch that is a collection. For example, if you have a list of foos and you create a new foo and the list needs to be refreshed:

 connect(({ name }) => ({
    foosFetch: '/foos',
    createFoo: name => ({
      fooCreation: {
        method: 'POST',
        url: '/foos',
        andThen: () => ({
          foosFetch: {
            url: '/foos',
            refreshing: true
          }
        })
      }
    })
  }))

catch and andCatch are similar, but for error cases.

Identity Requests: Static Data & Transforming Responses

To support static data and response transformations, there is a special kind of request called an "identity request" that has a value instead of a url. The value is passed through directly to the PromiseState without actually fetching anything. In its pure form, it looks like this:

connect(props => ({
  usersFetch: {
    value: [
      {
        id: 1,
        name: 'Jane Doe',
        verified: true
      },
      {
        id: 2,
        name: 'John Doe',
        verified: false
      }
    ]
  }
}))(Users)

In this case, the usersFetch PromiseState will be set to the provided list of users. The use case for identity requests by themselves is limited to mostly injecting static data during development and testing; however, they can be quite powerful when used with request chaining. For example, it is possible to fetch data from the server, filter it within a then function, and return an identity request:

connect(props => ({
  usersFetch: {
    url: `/users`,
    then: (users) => ({
      value: users.filter(u => u.verified)
    })
  }
}))(Users)

Note, this form of transformation is similar to what is possible on the PromiseState (i.e. this.props.usersFetch.then(users => users.filter(u => u.verified))); however, this has the advantage of only being called when usersFetch changes and keeps the logic out of the component.

Identity requests can also be provided a Promise (or any "thenable") or a Function. If value is a Promise, the PromiseState will be pending until the Promise is resolved. This can be helpful for asynchronous, non-fetch operations (e.g. file i/o) that want to use a similar pattern as fetch operations. If value is a Function, it will be evaluated with no arguments and its return value will be used instead, as in cases described above. The Function will only be called when comparison changes. This can be helpful for cases where you want to provide an identify request, but it is expensive to evaluate. By wrapping it in a function, it is only evaluated when something changes.

connect(props => ({
  userFetch: {
    comparison: props.userId,
    value: () => SomeExternalAPI.getUser(`/users/${props.userId}`)
  }
}))(Users)

Accessing Headers & Metadata

Both request and response headers and other metadata are accessible. Custom request headers can be set on the request as an object:

connect(props => ({
  userFetch: {
    url: `/users/${props.userId}`,
    headers: {
      FOO: 'foo',
      BAR: 'bar'
    }
  }
}))(Profile)

The raw Request and Response can be accessed via the meta attribute on the PromiseState. For example, to access the a response header:

userFetch.meta.response.headers.get('FOO')

Do not attempt to read bodies directly from meta.request or meta.response. They are provided for metadata purposes only.

Setting defaults and hooking into internal processing

It is possible to modify the various defaults used by React Refetch, as well as substitute in custom implementations of internal functions. A simple use case would be to avoid repeating the same option for every fetch block:

import { connect } from 'react-refetch'
const refetch = connect.defaults({
  credentials: 'include'
})

refetch(props => ({
  userFetch: `/users/${props.userId}`
}))(Profile)

A more advanced use case would be to replace the buildRequest internal function to, for example, modify headers on the fly based on the URL of the request, or using advanced Request options:

// api-connector.js
import { connect } from 'react-refetch'
import urlJoin from 'url-join'
import { getPrivateToken } from './api-tokens'

const baseUrl = 'https://api.example.com/'

export default connect.defaults({
  buildRequest: function (mapping) {
    const options = {
      method: mapping.method,
      cache: 'force-cache',
      referrer: 'https://example.com',
      headers: mapping.headers,
      credentials: mapping.credentials,
      redirect: mapping.redirect,
      mode: mapping.mode,
      body: mapping.body
    }

    if (mapping.url.match(/private/)) {
      options.headers['X-Api-Token'] = getPrivateToken()
    }

    if (mapping.url.match(/listOfServers.json$/)) {
      options.integrity = 'sha256-BpfBw7ivV8q2jLiT13fxDYAe2tJllusRSZ273h2nFSE='
    }

    return new Request(urlJoin(baseUrl, mapping.url), options)
  }
})

// ProfileComponent.js
import connect from './api-connector'
connect(props => ({
  userFetch: `/users/${props.userId}`,
  serversFetch: `/listOfServers.json`
}))(Profile)

You can also replace the handleResponse function, which takes a Response, and should return a Promise that resolves to the value of the response, or rejects based on the body, headers, status code, etc. You can use it, for example, to parse CSV instead of JSON:

// api-connector.js
import { connect } from 'react-refetch'
import { parse } from 'csv'

const csvConnector = connect.defaults({
  handleResponse: function (response) {
    if (response.headers.get('content-length') === '0' || response.status === 204) {
      return
    }

    const csv = response.text()

    if (response.status >= 200 && response.status < 300) {
      return csv.then(text => new Promise((resolve, reject) => {
        parse(text, (err, data) => {
          if (err) { reject(err) }
          resolve(data)
        })
      }))
    } else {
      return csv.then(cause => Promise.reject(new Error(cause)))
    }
  }
})

csvConnector(props => ({
  userFetch: `/users/${props.userId}.csv`
}))(Profile)

On changing the fetch and Request implementations

Through this same API it is possible to change the internal fetch and Request implementations. This could be useful for a number of reasons, such as precise control over requests or customisation that is not possible with either buildRequest or handleResponse.

For example, here's a simplistic implementation of a "caching fetch," which will cache the result of successful requests for a minute, regardless of headers:

import { connect } from 'react-refetch'

const cache = new Map()
function cachingFetch(input, init) {
  const req = new Request(input, init)
  const now = new Date().getTime()
  const oneMinuteAgo = now - 60000
  const cached = cache.get(req.url)

  if (cached && cached.time < oneMinuteAgo) {
    return new Promise(resolve => resolve(cached.response.clone()))
  }

  return fetch(req).then(response => {
    cache.set(req.url, {
      time: now,
      response: response.clone()
    })

    return response
  })
}

connect.defaults({ fetch: cachingFetch })(props => ({
  userFetch: `/users/${props.userId}`
}))(Profile)

When using this feature, make sure to read the fetch API and interface documentation and all related topics. Notably, you need to keep in mind that the body of a Response can only be consumed once, so if you need to read it in your custom fetch, you also need to recreate a brand new Response (or a .clone() of the original one if you're not modifying the body) so React Refetch can work properly.

This is an advanced feature. Use existing declarative functionality wherever possible. Customise buildRequest or handleResponse if these can work instead. Please be aware that changing the fetch (or Request) implementation could conflict with built-in current or future functionality.

Unit Testing Connected Components

For unit testing components connected, a non-default export of the unconnected component can be exposed to allow unit tests to inject their own PromiseState(s) as props. This allows for unit tests to test both success and error scenarios without having to deal with mocking HTTP, timing of responses, or other details about how the PromiseState(s) is fulfilled -- instead, they can just focus on asserting that the component itself renders the PromiseState(s) correctly in various scenarios.

The recommended naming convention for the unconnected component is to prepend an underscore to the component name. For example, if there is a component called Profile, add a non-default export of _Profile before the default export with connect:

class Profile extends React.Component {
  static propTypes = {
    userFetch: PropTypes.instanceOf(PromiseState).isRequired,
  }

  render() {
    const { userFetch } = this.props

    if (userFetch.pending) {
      return <LoadingAnimation/>
    } else if (userFetch.rejected) {
      return <ErrorBox error={userFetch.reason}/>
    } else if (userFetch.fulfilled) {
      return <User user={userFetch.value}/>
    }
  }
}

export { Profile as _Profile }

export default connect(props => ({
  userFetch: `/users/${props.userId}`
}))(Profile)

Now, unit tests can use the static methods on PromiseState to inject their own PromiseState(s) as props. For example, here is a unit test using Enzyme to shallow render the unconnected _Profile and provides a pending PromiseState and asserts that the LoadingAnimation is present:

const c = shallow(
  <_Profile
    userFetch={PromiseState.create()}
  />
)

expect(wrapper.find(LoadingAnimation)).to.have.length(1)

Similarly, the rejected and fulfilled cases can be tested:

const expectedError = new Error('boom')

const c = shallow(
  <_Profile
    userFetch={PromiseState.reject(expectedError)}
  />
)

expect(c.find(ErrorBox).first().prop().error).toEqual(expectedError)
const user = new User()

const c = shallow(
  <_Profile
    userFetch={PromiseState.resolve(user)}
  />
)

expect(wrapper.find(User)).to.have.length(1)

Complete Example

This is a complex example demonstrating various feature at once:

import React, { Component, PropTypes } from 'react'
import { connect, PromiseState } from 'react-refetch'

class Profile extends React.Component {
  static propTypes = {
    params: PropTypes.shape({
      userId: PropTypes.string.isRequired,
    }).isRequired,
    userFetch: PropTypes.instanceOf(PromiseState).isRequired
    likesFetch: PropTypes.instanceOf(PromiseState).isRequired
    updateStatus: PropTypes.func.isRequired
    updateStatusResponse: PropTypes.instanceOf(PromiseState) // will not be set until after `updateStatus()` is called
  }

  render() {
    const { userFetch, likesFetch } = this.props

    // compose multiple PromiseStates together to wait on them as a whole
    const allFetches = PromiseState.all([userFetch, likesFetch])

    // render the different promise states
    if (allFetches.pending) {
      return <LoadingAnimation/>
    } else if (allFetches.rejected) {
      return <Error error={allFetches.reason}/>
    } else if (allFetches.fulfilled) {
      // decompose the PromiseState back into individual
      const [user, likes] = allFetches.value
      return (
        <div>
          <User data={user}/>
          <Likes data={likes}/>
        </div>
      )
    }

    // call `updateStatus()` on button click
    <button onClick={() => { this.props.updateStatus("Hello World")} }>Update Status</button>

    if (updateStatusResponse) {
      // render the different promise states, but will be `null` until `updateStatus()` is called
    }
  }
}

// declare the requests for fetching the data, assign them props, and connect to the component.
export default connect(props => {
  return {
    // simple GET from a URL injected as `userFetch` prop
    // if `userId` changes, data will be refetched
    userFetch: `/users/${props.params.userId}`,

    // similar to `userFetch`, but using object syntax
    // specifies a refresh interval to poll for new data
    likesFetch: {
      url: `/users/${props.userId}/likes`,
      refreshInterval: 60000
    },

    // declaring a request as a function
    // not immediately fetched, but rather bound to the `userId` prop and injected as `updateStatus` prop
    // when `updateStatus` is called, the `status` is posted and the response is injected as `updateStatusResponse` prop.
    updateStatus: status => ({
      updateStatusResponse: {
        url: `/users/${props.params.userId}/status`,
        method: 'POST',
        body: status
      }
    })
  }
})(Profile)

TypeScript

If you are using React Refetch in a project that is using TypeScript, this library ships with type definitions.

Below is an example connected component in TypeScript. Note how there is both an OuterProps and InnerProps. The OuterProp are the props the component receives from the outside. In this example, the OuterProps would just be userId: string the caller is expected to pass in (e.g. <UserWidget userId="user-123"/>). The InnerProps are the PromiseState props that the connect() function injects into the component when fetching data. Since the InnerProps include the OuterProps, they are defined as InnerProps extends OuterProps and then the component itself extends React.Component<InnerProps>. This allows the component to have access to both the userId: string and userFetch: PromiseState<User> internally. However, the connect function returns a component with only the OuterProps (e.g. React.Component<OuterProps>) so callers only need to pass in userId: string.

interface OuterProps {
    userId: string
}

interface InnerProps extends OuterProps {
    userFetch: PromiseState<User>
}

class UserWidget extends React.Component<InnerProps> {
  render() {
    return (
      <ul>
        <li>{ this.props.userId }</li>
        <li>{ this.props.userFetch.fulfilled && this.props.userFetch.value.name }</li>
      </ul>
    )
  }
}

export default connect<OuterProps, InnerProps>((props) => ({
  userFetch: `/users/${props.userId}`
}))(UserWidget)

API Documentation

Support

This software is provided "as is", without warranty or support of any kind, express or implied. See license for details.

License

MIT

react-refetch's People

Contributors

aaronschwartz avatar agraboso avatar apalm avatar dstarner avatar ellbee avatar esamattis avatar eyalw avatar gaearon avatar gnoff avatar grrowl avatar hnordt avatar ipanasenko avatar istarkov avatar jhollingworth avatar jsullivan avatar loris avatar mattydoincode avatar mikekidder avatar moretti avatar nfcampos avatar oliviertassinari avatar passcod avatar priteshjain avatar pspsynedra avatar ratson avatar ryanbrainard avatar timdorr avatar timtyrrell avatar weekwood avatar ykikura-indeed 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  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  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  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

react-refetch's Issues

postsFetch is undefined

Not sure if it's something I'm doing stupidly wrong this evening or something's not right...

In my code I have react-refetch:

import { connect } from 'react-refetch'

I have my component:

export default class PostFeed extends React.Component {
  constructor(props) {
    super(props)
  }

  render() {
    const { postsFetch } = this.props

    if (postsFetch.pending) {
      return <span>Loading Posts...</span>
    } else if (postsFetch.rejected) {
      return <span>Failed to load posts</span>
    } else if (postsFetch.fulfilled) {
      return (
        <Post>
          {postsFetch.value}
          <span>This is a post</span>
        </Post>
      )
    }
  }
}

and I have my refetch connect...

connect((props) => ({
  postsFetch: `https://api.github.com/users/${props.user}/gists`,
}))(PostFeed)

and all I'm getting is that postsFetch is undefined.

Any ideas?

PromiseState and any other kind of promised props

So I've found a kind of sideways use for the ideas of PromiseState and connect (as a HOC that computes additional async props from your regular props). Components that need to compute props asynchronously derived from the other props need most of the ideas behind react-refetch (the props need to be represented as something that can be fulfilled, rejected, pending; it needs figure out whether to recompute when props change). In a way it's a lower-level primitive on top of which react-refetch is built. Do you think it belongs in react-refetch in any way?

I'm using it like this:

export default withPromisedProps({
  table: {
    dependentProps: ['file'], // every time one of these props changes table is recomputed
    then: ({file}) => promisedFileReader(file).readAsText().then(csvParse)
  }
})(CsvTable)

Not sure if this is relevant to anyone, feel free to close this issue :)

Rejected promises don't get error messages in IE8

Hi,

I'm not sure if IE8 is supposed to be supported or not, but after polyfilling all of the things this library almost works perfectly.

The only issue I've encountered is that IE8 refuses to accept a message for the error that is thrown when rejecting promises because of the second id parameter. If you delete the id then everything seems to work fine.

As far as I can tell Error isn't supposed to have a second argument anyway so I'm not sure what the id is for, but it could be handled with a custom error type that does take a second argument - this could also be useful to support passing more than just a message on a server error.

Supply custom fetch() implementation

It would be great if a custom fetch() implementation could be supplied to React Refetch. My usecase would be not using a completely custom implementation (although I think that could be useful, too), but doing something like this:

function customFetch (input, init = {}) {
  init.credentials = 'include'
  // do something on the input, too
  return window.fetch(input, init)
  .then(response => preprocess(response))
}

As well as implementing a kind of caching proxy that maintains a cache of responses and provides them directly from memory if Refetch asks for them based on some conditions (say, time since last request for that url, or window.onLine === false, or the heartbeat signal we use to check for effective offlineness, etc).

support falsy values for value in mapping?

Hi,

The condition at https://github.com/heroku/react-refetch/blob/master/src/components/connect.js#L51 causes a request like

connect(props => {
  return {
    blahFetch: {
      url: '/some/url'
      then: value => {
        if (value.some.key)
          return '/some/other/url'
        else
          return {value: null}
      }
    }
  }
})(MyComponent)

to be invalid. I understand the need to validate there is a url or value, however, how should I do a request like this? (ie. a request in which you poll a first url, you use the response of that to check whether something exists, if it exists you do the request you really want, otherwise that first request doesn't need a value)

Nuno

Integration with Redux Form

Would be awesome if "lazy fetches" returns a promise, as Redux Form expects a promise to be passed to handleSubmit we'll be able to do things like this:

(PromiseState doesn't help in this case, because it'll be available only after triggering handleSubmit)

import React from 'react';
import { reduxForm } from 'redux-form';
import { connect } from 'react-refetch';
import Panel from '@hnordt/reax-panel';
import PanelBody from '@hnordt/reax-panel-body';
import Form from '@hnordt/reax-form';
import Alert from '@hnordt/reax-alert';
import FormGroup from '@hnordt/reax-form-group';
import Label from '@hnordt/reax-label';
import Input from '@hnordt/reax-input';
import Button from '@hnordt/reax-button';
import Spinner from '@hnordt/reax-spinner';
import { isEmpty } from '@hnordt/reax-validator';

const ProjectForm = ({
  fields: { name },
  submitting,
  error,
  handleSubmit,
  resetForm,
  postProject
}) => (
  <Panel title="Add Project">
    <PanelBody>
      <Form onSubmit={handleSubmit(data => postProject(data).then(resetForm))}>
        {error && <Alert type="danger">{error}</Alert>}
        <FormGroup error={name.touched && name.error}>
          <Label>Name</Label>
          <Input {...name} disabled={submitting} />
        </FormGroup>
        <Button type="primary" submit disabled={submitting}>
          {submitting ? <Spinner /> : 'Save'}
        </Button>
      </Form>
    </PanelBody>
  </Panel>
);

// ES7 decorators will bring a better syntax in the future :)
export default reduxForm(
  {
    form: 'project',
    fields: ['name'],
    validate: ({ name }) => {
      return {
        name: isEmpty(name) && 'Required'
      };
    }
  }
)(connect(() => ({
  postProject: data => ({
    postProjectResponse: {
      url: 'https://httpbin.org/post',
      method: 'POST',
      body: JSON.stringify(data)
    }
  })
}))(ProjectForm));

Incompatible with stateless authentication

I'm using JWT's as my authentication mechanism in my SPA, persisted to window.sessionStorage. When I make calls to my API, I configure the request with an Authorization: Bearer TOKEN header that authorizes the request.

Since API calls in react-refetch are defined outside the context of the component class itself, they cannot pick up changes during runtime to get the current token.

Here's an overview of the flow:

  1. User loads the application on a hard server-request; app initializes in the client, and refetch-enabled components are loaded.

    Refetch configuration on a protected route like ...

    // lib.js
    export const jwt = () => sessionStorage.token;
    export const authHeader = () => {
      if (jwt()) return { 'Authorization': `Bearer ${jwt()}` };
      return {};
    };
    
    // protected_component.js
    connect(() => ({ fetchStuff: { url: '/api/stuff', headers: authHeader() }})(Component);

    ... assign headers: {} since the user starts off logged-out, thus no token is present in window.sessionStorage.

  2. User logs in. Login handler writes the returned, valid token to window.sessionStorage.

    // lib.js
    export const login = ({ token }) => {
      sessionStorage.setItem('token', token);
    };
    
    // login.js
    componentWillReceiveProps(nextProps) {
      if ((nextProps.postLoginResponse || {}).fulfilled) {
        login(nextProps.postLoginResponse.value);
        this.context.router.push({ pathname: '/' });
      }
    }
  3. User accesses protected resource /stuff and refetch fails, because the API request was made with no Authorization header (from Step 1).

    GET http://domain/stuff 403 (Forbidden)

For now, I'm working around the issue by changing:

this.context.router.push({ pathname: '/' });

... to ...

window.location = '/';

But I don't consider that an optimal solution because I have to re-initialize the entire app on successful login, which seems excessive.

Is there any other way around this? Or an alternative approach?

Warning shown when component is unmounted while refetch request is pending

If a user clicks on a button that unmounts the current component while the component's refetch request is pending, the following warning will be shown in the console after the refetch request is complete:

Warning: setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op. Please check the code for the Refetch.connect(PostList) component.

Are we supposed to cancel the refetch request within componentWillUnmount() ? How can we do that?

Doc example not compiling

I've been hacking at this for a while now, but for some reason can't get the example from the docs below to compile:

connect(({ name }) => ({
   foosFetch: '/foos',
   createFoo: name => {
     method: 'POST',
     url: '/foos',
     andThen: () => {
       foosFetch: {
         url: '/foos',
         refreshing: true
       }
     }
   }
 }))

The error message given is:

Module build failed: SyntaxError: /Users/Joe/Documents/demo/client/app/bundles/demo/startup/Root.jsx: Unexpected token (108:8)
18:30:26 client.1 |   106 |    createFoo: name => {
18:30:26 client.1 |   107 |      method: 'POST',
18:30:26 client.1 | > 108 |      url: '/foos',
18:30:26 client.1 |       |         ^
18:30:26 client.1 |   109 |      andThen: () => {
18:30:26 client.1 |   110 |        foosFetch: {
18:30:26 client.1 |   111 |          url: '/foos',

In my own code, I've been trying to make it possible to delete a record and then refresh the data , and it seems as though the example above would allow me to do that, but it doesn't seem to compile. The other snippets given do compile fine

I've tried updating all of my dependencies,restarting my server and a whole bunch of different combinations, but I've only been able to get things to work by wrapping foosFetch and createFoo in parenthesis. This doesn't have the same functionality though and prevents me from modifying the "name" props, which prevents me from refetching automatically.

My work around so far has been to fetch data using refetch but then in my root react component I have to handle all of the logic for updating there:
ie.

  _destroy(id) {
    this.props.destroy(id);
    this.props.refresh();
  }

Easy way to register to for a one time promise callback?

Rendering different promise statuses (pending, setteled, etc) is easy (yay!).
Performing a function one-time once a promise settles seems hard.
It's very common that I want to perform some logic when a promise is settled - for example:

  • forms (load data into state): fetch form data, once available, setState({ data: value }).
  • forms (post data, then do something): when submitting a form - on success, redirect to so other page (with react-router), or then - show success toaster.

if i do this:

  // no good for me
  componentWillReceiveProps(nextProps) {
    nextProps.fetchAccountPs.then(account => this.setState({ account }));
  }

It gets called every time props change, even though the fetch promise does not change, not good. I only want it to get called once. when (ps.pending => ps.setteled).
if the promise mapping changes and fetch occurs again, only then call the .then() again.

right now I need to keep track of when (ps.pending => ps.setteled) happens myself which is tedious.
would be really nice to be able to do

connect({
  fetchAccountPs: {
     method: "GET",
     url: "/some/url",
     callback: "onAccountFetched"    // <==  suggestion
  }
)...

and the HOC would call my component exposed onAccountFetched(value) once, using a ref.

what do you think?
is there another existing way i'm missing?

Create TodoMVC Example

React Refetch has a lot of example snippets, but not a working complete example app. This is an ask to anyone out there who would like to create an example app based on TodoMVC (http://todomvc.com).

Request equality does not consider default request attributes

Requests are compared before defaults are applied, so if one request depends on an implicit default attribute and one explicitly declares the default attribute, they will be considered not equal.

For example (reported in #26), the first deviceMessageSearch has an implicit method : 'GET', but the second deviceMessageSearch has an explicit method : 'GET'. Even though the two are essentially equal, they are considered different requests and fetched again one time on this.props.refreshMessages():

export default connect((props) => {
  const deviceMessageUrl = `${process.env.API_URL}api/users/${props.params.userId}/device-messages`;
  return {
    deviceMessageSearch : deviceMessageUrl,
    refreshMessages : () => ({
      deviceMessageSearch : {
        url : deviceMessageUrl,
        method : 'GET',
        refreshing : true
      },
    }),
  };
})(DeviceMessages)

The fix is probably to break out the defaults from buildRequest() and apply them during request coercion so they are memoized and compared during the equality check.

cc: @jwdotjs

Passthrough meta on all requests

Currently, meta only works if value is also set (i.e. only for identity requests). I'm thinking that a better way would be for meta to work for URL-based requests too and for request and response to be merged into meta. This would allow applications to add arbitrary metadata to any request and make it accessible to the component. I don't have a great use case of that off hand, but I like that it makes identity requests more "normal." The downside I see that meta currently allows any data type, but if we go this route, it would have to be an object. Thoughts?

RR with Redux

I'm opening this issue to start a discussion on how to use both RR and Redux together.

My first idea is something like:

class Foo extends React.Component {
  componentWillReceiveProps(nextProps) {
    const { dispatch } = this.props; // Injected by Redux
    if (nextProps.fooFetch.fulfilled) { // Injected by RR
      dispatch(updateFoo(nextProps.fooFetch.value)); // updateFoo is an action and we pass PS.value as payload
    }
  }
}

// normal RR/Redux connects...

I don't see any problems with this approach. @gaearon thoughts?

Worth noting: if your app don't need to maintain local state, Redux/Flux is optional (https://github.com/heroku/react-refetch#motivation)

Clicking back button loads JSON representation in Rails

I've just started implementing RR in a Ruby on Rails app and I seem to be running into an issue where if I navigate to another page and then click the back button, the JSON file that was rendered via the connect call is what loads on the page. Has anyone hit this issue before?

In my console, my sequence of commands looks like this:

On page load:

# Loading the template
 | Started GET "/" for ::1 at 2016-02-25 18:31:53 -0500
 | Processing by SurveysController#index as HTML
...
# Loading the JSON data via the connect call
 | Started GET "/" for ::1 at 2016-02-25 18:31:54 -0500
 | Processing by SurveysController#index as JSON

Then if I navigate to another page and click the back button, only the JSON data loads.

My controller looks like:

  # Get all surveys and return them
  # {Surveys: [survey_one,survey_two,...]}
  def index
    surveys = Survey.where(user_id: current_user.id)

    respond_to do |format|
      format.html
      format.json { render :json => { surveys: surveys } }
    end
  end

Could the problem be that I'm using Rails for routing? It seems like the only apps I've seen implementing RR use React-Router instead

Offline Support

I'm working on a project that needs offline support and I don't want to use Flux, because all state is saved on server-side and I don't wanna duplicate/manage local state.

Would be awesome if we can provide our own implementation of handleResponse, so we can implement something like this:

// myOwnHandleResponse.js

import localforage from 'localforage';

const getRequestId = request => {
  // TODO: md5 or something like that :P
  return `${request.url}.${request.method}.${JSON.stringify(request.headers)}`;
};

// On response success update offline cache and return json
// On response failure warn and return the cached json
const handleResponse = (request, response) => {
  const requestId = getRequestId(request);
  if (response.status >= 200 && response.status < 300) { // Or response.ok
    const json = response.json();
    // localforage.setItem() resolves the value that was set :)
    return localforage.setItem(requestId, json).catch(error => {
      console.warn('Failed to update offline cache', { requestId, request, error });
      return json;
    });
  } else {
    return localforage.getItem(requestId);
  }
};

export default handleResponse;

We'll need to implement a timeout in React Refetch and implement a way to handle POST/PUT/DELETE requests.
It's just the initial idea. Toughts?

No way to access json value of an rejected request

My server returns status 400 (bad request) intentionally for bad data in a form, and I wish to read the json body that comes along with the response, explaining where that error is and what is it.
It seems the promise API does not allow me to read the error? Please help..
(I also tried messing around with Response object, and reading the json() stream, but no success)

screen shot 2016-02-02 at 11 23 06 am

image

Issues in Safari on iOS

It looks like there are a couple of bugs in iOS. The first one is that a polyfill is required for Object.assign. Secondly, the PromiseState fails to resolve in iOS. I'm using the latest release candidate.

Should manual request return promise?

When doing requests from event handlers, I wanted to be notified when request finishes, so that I could show message to the user. Like this:

onSave() {
  this.props.updateData(this.state.data).then(() => flash("Saved"))
}

I'm not sure what value should be passed to the promise though.

Custom error handling

I'm using a RESTful API that when I get a validation error the following response is thrown:

{ "errors": { "field1": "Field is required", "field2": "Field is required", ... } }

They react-refetch is handling promise reject rejection is by supporting a single error that must be a string. Passing an object will result in having the error message "[object Object]" due to string casting of the response JSON...

We must either have support for custom error handling OR at least get access to to the original response somehow.

Static Data not immediately fulfilled?

Maybe I'm misunderstanding something, but I'd assume that static data definitions like the following:

export default connect((props) => ({
  userFetch: { value: { id: 1, name: 'Tigger' }}
})(Component);

... would be available immediately, say, in the initial render:

render() {
  const user = this.props.userFetch.value;
}

However, it seems that on the initial render, this.props.userFetch.pending is true. I can't seem to get access to the static data until componentWillReceiveProps.

Shouldn't the PromiseState for a static data definition be immediately fulfilled?

Side Effects After Posting Data

What's the best practice to handle side effects after posting data?

Here is my approach:

export default connect(({ history }) => ({
  saveCondition: condition => ({
    saveConditionResponse: {
      method: 'POST',
      url: '/medical/condition',
      body: JSON.stringify(condition),
      andThen: newCondition => {
        history.push(`/medical/${newCondition.id}`);
        return {};
      }
    }
  })
}))(ConditionFormContainer);

Forms

Hello.

I would like to share a HOC I've made to be used with React Refetch:

https://github.com/hnordt/reax-stateful-form

While it's working and I'm using in production, I would like to hear suggestions from the community to handle more form use cases.

The main idea is that the HOC maps common properties to each field, so when you type <TextInput {...foo} /> you'll end up with <TextInput name={foo.name} value={foo.value} touched={foo.touched} error={foo.error} />.
You'll have also isValid (boolean) and handleSubmit that will return a promise with the mapped values when resolved or the first field with error when rejected.

PS.: I stole most of the ideas from the awesome @erikras's Redux Form.

Add setVariables-like functionality to refetch, as in Relay

At the moment the connect() is a function of props alone, so there is no way for an object to change what it currently displays (think about a timeline graph component with a timerange selection - when range changes, different data should be loaded).

If we add somehting something like "setVariables()" which is a little similar to doing setState() on the HOC connect, we can achieve this.
see Relay specs:
https://facebook.github.io/relay/docs/api-reference-relay-container.html

what do you think?

then/andThen with empty response body

With the following:

connect((props) => {
  fetchPrefs: '/api/prefs',
  deletePref: (id) => ({
    doDeletePref: {
      url: `/api/prefs/${id}`,
      method: 'DELETE',
      andThen: () => ({
        url: '/api/prefs',
        force: true,
        refreshing: true,
      })
    })
  }),
})(Component)

Invoking deletePref() never calls andThen on doDeletePref.

I've determined this is because my API returns a 204: No Content with an empty response body. If I change the response to be a 200: OK and return an empty JSON object, andThen fires normally and everything works.

I also tried returning a 200: OK with an empty body, and the andThen did _not_ fire.

So my guess is that andThen only fires if the response body is not empty.

Personally, I think andThen should fire if the response was successful, regardless if the response body is present.

NOTE: I encountered the same behavior with then.

Switch to isomorphic-fetch

The module, as it sits, is almost perfect for my use case. However, I need to render components server side too. Would you be open to a PR that replaces whatwg-fetch with a similar, standards compliant polyfill that also works in Node?

Feature request: Query params

Nice library, thanks for creating it!

What do you think about adding some convenience features?

Url query params

connect((props) => ({
  data: {
    url: "/api/data",
    query: { from: props.from, limit: props.limit }  // => "/api/data?from=xxx&limit=yyy
  }
}))(Component)

Filling data server side instead of on client side

There doesn't seem to be a mention of how one can use this library to fetch data and populate views on the server side. Is it possible to do so with this library à la react-resolver? It would be a nice addition for people looking to build completely isomorphic apps.

Feature request: Transform functions

(Split from #17)
What do you think about adding some convenience features?

Data transform functions

For cases where the data returned is inconvenient to work with directly. Maybe we can reuse then, but I think it's not possible now.

connect((props) => ({
  data: {
    url: "/api/data",
    transform: ((rawValue) => rawValue.real_data)
  }
}))(Component)

Custom Request Post-Processing

I really like this library, and I'd like to try it for a data-intensive app. Currently, I use d3's csv method to do this:

// (It's CSV, but GitHub Pages only gzip's JSON at the moment.)
d3.csv("large_dataset.csv", function(error, dat) {
   //work with dat
}

I implemented a version with react-refetch, that looks like this:

let AnalysisRefetch = connect((props) => ({
    fetchedData: `large_dataset.csv`
}))(Analysis)

But when I look into this.props.fetchedData, the promise is rejected with the reason "SyntaxError: Unexpected token ,".

I imagine this is because refetch was built for fetching JSON objects. But can I plug in a custom parser or so on the returned value? Or have access to the raw response, somehow? Using refetch will make things so much easier!

Thanks

add static version of PromiseState#_mapFlatMapValue ?

That method is useful when building components that receive a prop that may or may not be a PromiseState.

eg.

const Comp = ({table}) => {
  table = table instanceof PromiseState ? table : PromiseState.resolve(table)
  return (
    <div>
      {table.fulfilled && <span>{table.value.length}</span>}
    <div>
  )
}

(It should probably get a name like PromiseState.ensure(), mapFlatMapValue is kind of cryptic)

Sounds like a useful addition?

Compiled version of react-refetch

It seems like the only way to use react-refetch is by setting up webpack, babel, and the rest of the toolchain. I really like the simplicity of this library for putting together quick proof-of-concepts, for which I don't want to bother about setting up the webpack toolchain.

I couldn't find a single compiled js that I could use. I also didn't manage to create a pure compiled version using webpack. Is there a chance one such file could be included as a release? And potentially even added to cdnjs or so?

Working with containers

Hi, I was trying to use react-refetch putting the api calls in a container an passing them to a dump component. The issue is that I am not able to pass custom props like another container method to the dump component. Here the code:

Container:

import React, { Component } from 'react'
import { connect, PromiseState } from 'react-refetch'
import Form from '../components/Form'

export default class Edit extends Component {
  render() {
    const { getSchema, getResume, postResume, deleteResume } = this.props

    const allFetches = PromiseState.all([getSchema, getResume])

    if (allFetches.pending) {
        return <span>loading</span>
      } else if (allFetches.rejected) {
        return <span></span>
        return <span>{allFetches.reason}</span>
      } else if (allFetches.fulfilled) {
      const [schema, resume] = allFetches.value
        return <Form schema={schema} resume={resume} onPost={postResume} onDelete={deleteResume} />
        }
    }
}

export default connect(props => ({
  getSchema: '/api/schema',
  getResume: `/api/resume/${props.routeParams.name}`,
  postResume: resume => ({
    postResumeResponse: {
      url: `/api/resume/${props.routeParams.name}`,
      method: 'POST',
      body: JSON.stringify({ resume })
    }
  }),
}))(Edit)

Component:

import React, { Component } from 'react'

class form extends Component {
    log = (type) => console.log.bind(console, type);

    render() {
           console.log(this.props);
        const { resume, schema, postResume } = this.props

        const log = (type) => console.log.bind(console, type);

        return (
            <Form schema={schema}
            formData={resume}
            onChange={log("changed")}
            onSubmit={postResume}
            onError={log("errors")} />
        )
    }
}

export default form

Question About Refetching

export default connect((props) => {
  const url = '/api/devices';
  return {
    devicesSearch : url,
    refreshDevices : () => ({
      devicesSearch : {
        url,
        refreshing : true,
      },
    }),
  };
})(DevicesList);

I have a question about line 148 on connect.js (https://github.com/heroku/react-refetch/blob/master/src/components/connect.js#L148)

Currently, it checks if the mapping is equal between the previous request and the next one. From my local testing, this causes a mapping to be refetched only once, then that mapping will be equal to the previous mapping on subsequent requests.

In my example above, in the DevicesList component I have a button that allows the user to click and refresh the list to view the latest devices. They can click the button as many times as they want, but it will only make one request currently, then the equality check returns true between previous and next mapping so the subsequent refetches will fail and that seemed counter-intuitive (unless I'm doing something incorrectly).

Should I be adding additional keys to my mapping so that the comparison check returns false? Should I be passing in a comparison check based on something specific?

If not, it seems to me that it would make more sense here to see if the the mapping is still valid and always refetch regardless of equality, but I'm not sure what that would affect.

I created a local branch to set the refreshing flag to false after a request is complete if refreshing was true and in the default equality check I added refreshing to the array of keys to test against for equality, and that works, but it doesn't seem like a good solution since refreshing is an optional key for a refresh mapping. If a user didn't pass that key in they would still encounter the same issue so I wanted to get everyone's thoughts on other solutions.

Side-effects with the Refetch equivalent of Redux's "action creators"?

Related to the section on Posting + Refreshing Data, I'd like to push a new browser state after an update action. In my app, there is no separate view for an "edit" action: users can click an edit button, and the row reformats to inputs. My problem lies in redirecting back to the list view after the update action completes.

I have it working with the following:

import React, { Component } from 'react';
import { connect } from 'react-refetch';
import { authHeader } from 'lib';

class List extends Component {

  // ...

  componentWillReceiveProps(nextProps) {
    const { fetchPref: nextFetchPref } = nextProps;
    const { fetchPref } = this.props;

    if (fetchPref && nextFetchPref && fetchPref.pending && nextFetchPref.fulfilled) {
      this.context.router.push({ pathname: '/admin/prefs' });
    }
  }

  // ...

  render() {
    // omitting the rest of the JSX for the sake of brevity, but this is actually
    // a table where each row has an edit button that invokes `patchPref`
    // with the `id` for the row and the `data` from user input
    return (
      <a onClick={this.props.patchPref.bind(this, id, data)}>edit</a>
    );
  }
}

export default connect((props) => ({
  fetchPrefs: {
    url: '/api/prefs',
    headers: authHeader(),
  },
  patchPref: (id, data) => ({
    fetchPref: {
      url: `/api/prefs/${id}`,
      method: 'PATCH',
      body: JSON.stringify(data),
      headers: authHeader(),
      andThen: () => ({
        fetchPrefs: {
          url: '/api/prefs',
          headers: authHeader(),
          force: true,
          refreshing: true,
        }
      }),
    }
  }),
}))(List);

As you can see, I've had to do some this.props/nextProps checking in componentWillReceiveProps to support the behavior I'm after.

What I'd _like_ to do is define a then clause on patchPref so that I could invoke it along the lines of:

this.props.patchPref(id, data).then(() => {
  this.context.router.push({ pathname: '/admin/prefs' });
})

The intention being:

Do all the react-refetch stuff defined in connect for patchPref, then do this other thing.

That would allow me to completely delete componentWillReceiveProps.

As the return of this.props.patchPref() is undefined, and as then: and andThen: don't have access to this.context, it doesn't seem like my desired solution is possible currently.

I don't know if such a thing would be possible, or if there is another/cleaner way of accomplishing the same behavior with the library as it is now.

Was hoping to hear y'alls thoughts on this.

Identity Requests (value attribute)

Add a value attribute to requests (aka mappings) the return the value in lieu of actually fetching data from url. Requests with value are not allowed to also have a value.

This will support composable transformations, like this (from #21):

connect((props) => ({
  data: {
    url: "/api/data",
    then: (rawValue) => ({ 
      value: rawValue.real_data 
    })
  }
}))(Component)

and will also provide a way to create static PromiseStates, like this (from #19):

connect((props) => ({
    project: `/api/projects/${props.id}`,
    updateProject: (data) => ({
        project: { 
          url: `/api/projects/${props.id}`, 
          method: "PATCH", 
          body: data,
          andThen: () => ({
            projectUpdated: { 
              value: true // some static value of your choice
            }
          })
        }
    })
}))

POST action does not trigger the same request

When the first submit attempt failed (rejected), the user re-enter the details and execute upgradePlan again, but there was no HTTP request performed. Because, it's a POST request so I don't expect that it should be cached?!

submit() {
   this.props.upgradePlan(data)
}
...
export default connect(props => ({
  tokenFetch: `/api/v1/organisations/${props.params.organisationId}/payments/token`,
  upgradePlan: data => ({
    upgradePlanResponse: {
      url: `/api/v1/organisations/${props.params.organisationId}/payments/upgrade`,
      method: 'POST',
      body: JSON.stringify({ data })
    }
  })
}))(SubscriptionUpgrade)

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.