Inspired by Kris Jenkins' RemoteData Elm package, this library provides an object for representing remote data in your application.
npm install --save remote-data-js
By representing the data and the state of the request in one object it becomes impossible for you to have data that's out of sync.
A typical app might model the data as:
{ loading: true, data: undefined }
And then update the values when the request succeeds. However, this really is one piece of information that is now represented across two keys, and as such it can become out of sync.
Instead, RemoteData models both the request and the data in one object, so
they can never be out of sync with each other.
A RemoteData instance has one of four states:
NOT_ASKED- you've got started the request yetPENDING- the request is in flightSUCCESS- we have data from the requestFAILURE- the request went wrong, we have an error for it
You can check the status of a RemoteData instance and therefore represent data
in your application accordingly.
Additionally, RemoteData instances are never mutated, but pass a new version
of themselves through callbacks. This means any mutation bugs with rendering off
your remote data instances are not a concern, and that this library can play
nicely with React, Redux and others.
## Example
import RemoteData from 'remote-data'
const githubPerson = new RemoteData({
url: username => `https://api.github.com/users/${username}`,
onChange: remoteData => console.log('State changed!', remoteData),
})
// then later on
githubPerson
.fetch('jackfranklin')
.then(remoteData => {
// it worked fine
console.log(remoteData.isSuccess()) // true
console.log(remoteData.data) // github api data
console.log(remoteData.response.status) // 200
})
.catch(remoteData => {
// something went wrong
console.log(remoteData.isSuccess()) // false
console.log(remoteData.isFailure()) // true
console.log(remoteData.data) // error info
console.log(remoteData.response.status) // response status code
})### Creating RemoteData instances
The configuration you can provide when creating a new instance of RemoteData are as follows:
const instance = new RemoteData({
url: (name) => `https://api.github.com/users/${username}`
onChange: (newInstance) => {...},
parse: (response) => response.json,
fetchOptions: {}
});These are fully documented below:
-
url: String | Function: if given a string, this will be the URL that the request is made to. If it's a function it will be called whenfetchis called, passing any arguments through. For example,remoteData.fetch('jack')will call theurlfunction, passingjackas the argument. -
onChange: Function: a function called whenever the state of a remote data instance changes. This is passed in the new RemoteData instance. -
parse: Function: a function used to parse theResponsefrom the HTTP request. Defaults toresponse.json(). -
fetchOptions: Object: an object that is passed through tofetchand allows you to configure headers and any other request options.
### Making Requests
To make a request, call fetch on the RemoteData instance:
const githubPerson = new RemoteData({
url: name => `https://api.github.com/users/${username}`,
onChange: newGithubPerson => console.log(newGithubPerson),
})
githubPerson.fetch('jackfranklin')A promise is returned and the value it will resolve to is the new RemoteData
instance:
githubPerson.fetch('jackfranklin').then(newData => {
console.log(newData.data) // GitHub API data, parsed from JSON
console.log(newData.response.status) // status code
console.log(newData.state) // 'SUCCESS'
})You can call any of the following methods:
isFinished(): true if a request has succeeded or failed.isNotAsked(): true if the request hasn't been asked for (this is the default state).isPending(): true if the request has been started but is pendingisFailure(): true if the request has failedisSuccess(): true if the request has succeeded
You can "switch" on a RemoteData instance's state similarly to functional languages and the JavaScript Union Type package:
githubPerson.fetch('jackfranklin').then(data => {
const message = data.case({
NotAsked: () => 'Initializing...',
Pending: () => 'Loading...',
Success: data => renderData(data),
Failure: error => renderError(error),
})
})If you don't handle all four possible states, you must include a default handler
named _ (underscore):
githubPerson.fetch('jackfranklin').then(data => {
const message = data.case({
Success: data => renderData(data),
Failure: error => renderError(error),
_: () => 'Loading...',
})
})You can call .data on a request to access the data, but be aware that this
will throw an error if the request hasn't been asked for or is pending.
You can call .response on a request to access the response, but be aware that
this will throw an error if the request hasn't been asked for or is pending.
Let's say you have your own custom API library in your app for making API
requests that returns promises. In this instance, you don't want to use
RemoteData's own fetch based API to initiate the request, but instead you want
to wrap your promise in a RemoteData instance:
import { fromPromise } from 'remote-data-js'
import myCustomApiRequestLib from 'my-custom-lib'
const onChange = newRemoteData => {...}
const apiRequest = myCustomApiRequestLib('/foo')
const remoteDataInstance = fromPromise(apiRequest, { onChange })
remoteDataInstance.isPending() // => true