• Stars
    star
    149
  • Rank 248,619 (Top 5 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 8 years ago
  • Updated over 3 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Dealing with remote data and all its states properly in JavaScript applications.

RemoteData.js

Inspired by Kris Jenkins' RemoteData Elm package, this library provides an object for representing remote data in your application.

Build Status

npm install --save remote-data-js

Motivations

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 yet
  • PENDING - the request is in flight
  • SUCCESS - we have data from the request
  • FAILURE - 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
  })

API

### 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 when fetch is called, passing any arguments through. For example, remoteData.fetch('jack') will call the url function, passing jack as 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 the Response from the HTTP request. Defaults to response.json().

  • fetchOptions: Object: an object that is passed through to fetch and 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'
})

Checking the status of a request

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 pending
  • isFailure() : true if the request has failed
  • isSuccess() : 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.

Making remote data instances from a promise.

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

More Repositories

1

gulp-load-plugins

Automatically load in gulp plugins
JavaScript
756
star
2

test-data-bot

TypeScript
666
star
3

dotfiles

My dotfiles for my dev environment, compromising of tmux, vim, zsh and git.
Lua
235
star
4

jQuery-Form-Validator

Got bored of using other ones, so made my own
JavaScript
233
star
5

pulldown

The minimal JavaScript package manager.
JavaScript
175
star
6

demopack

A prepackaged Webpack for easy frontend demos.
JavaScript
172
star
7

universal-react-example

An example Universal ReactJS application
JavaScript
144
star
8

the-refactoring-tales

HTML
138
star
9

tilvim

TIL Vim: Short posts on Vim tips and tricks
HTML
89
star
10

tweet-parser

Parsing tweets into lists of entities.
JavaScript
76
star
11

react-css-modules-webpack

React + Webpack Dev Server + Hot Reloading + CSS Modules
JavaScript
72
star
12

jspm-es6-react-example

JavaScript
69
star
13

fetch-factory

Easy JS objects for talking to your APIs
JavaScript
67
star
14

jspm-dev-builder

Incremental development builds with jspm
JavaScript
66
star
15

elmplayground

An Elm blog, written in Elm, about Elm.
Elm
63
star
16

react-remote-data

JavaScript
57
star
17

so-fetch

TypeScript
57
star
18

html-dist

A tool for editing HTML files to add new scripts
JavaScript
47
star
19

javascriptplayground.com

HTML
39
star
20

react-hot-load-webpack-boilerplate

JavaScript
37
star
21

doccy

Generate Markdown documentation from JavaScript
JavaScript
31
star
22

elm-for-js-developers-talk

Elm
30
star
23

vue2-demo-proj

JavaScript
28
star
24

react-training-workshop

Code, notes and more for a day long React workshop.
JavaScript
27
star
25

todo-react-testing

A silly small React TODO app used in a blog post about testing React apps.
JavaScript
25
star
26

rollup-plugin-markdown

JavaScript
23
star
27

react-no-webpack-required

Using React without Babel & Webpack
JavaScript
22
star
28

do-you-even-elm

How much Elm do you do?
Elm
21
star
29

node-todo

A Node.js & Express.js todo app
JavaScript
19
star
30

vscode-go-to-file

TypeScript
18
star
31

svg-to-elm

TypeScript
17
star
32

Forrst-API-jQuery-Wrapper

A jQuery wrapper for the Forrst API. As the Forrst API grows, so will this.
JavaScript
17
star
33

elm-boilerplate

Starting point for Elm-Lang projects
JavaScript
17
star
34

interactive-es6

Learn ES6 in your browser in an app built in ES6.
JavaScript
16
star
35

responsiveImages

Responsive Images in JavaScript!
CoffeeScript
16
star
36

jspm-es6-example

JavaScript
16
star
37

doubler

Simple doubles for JS testing
JavaScript
14
star
38

react-ast-viewer

An Abstract Syntax Tree browser, written in React
JavaScript
14
star
39

pure-react-forms

JavaScript
14
star
40

JavaScript-Playground--Simple-jQuery-PubSub

Code for the blog post on JavaScriptPlayground.com on a simple jQuery PubSub
JavaScript
13
star
41

cannon-blog

A ReactJS blogging engine
JavaScript
13
star
42

jspm-es6-angular-example

JavaScript
13
star
43

totesy

My own TODO app
JavaScript
12
star
44

elm-game-of-life

Building Conway's Game of Life in Elm
Elm
12
star
45

JS-Regex

Live JS Regular Expression Testing
JavaScript
12
star
46

prettier-scripts

Some shell scripts for Prettier.
JavaScript
12
star
47

github-proxy

GitHub API but cached and offline-able.
JavaScript
11
star
48

authoring-es6-module-example

JavaScript
10
star
49

node_cli_router

A router for parsing command line flags and arguments in your Node CLI scripts.
JavaScript
9
star
50

wouldlike.js

JavaScript
8
star
51

client-webpack-boilerplate

A teeny client side JS webpack boilerplate to get up and running quickly.
JavaScript
8
star
52

react-fundamentals-2019-workshop

JavaScript
7
star
53

skillswap

Share your skills with others and find people to help you learn new things.
JavaScript
7
star
54

half-stack-webpack

JavaScript
7
star
55

zip-list

TypeScript
7
star
56

testing-react-with-jest

JavaScript
7
star
57

react-introduction-exercises

JavaScript
7
star
58

universal-react-talk

JavaScript
7
star
59

jQuery-UK-2012-Conference-Notes

6
star
60

elm-github-info

Fetching info from GitHub using Elm
Elm
6
star
61

ST2-MDN-Search

Search the MDN from within Sublime Text 2
Python
6
star
62

ng2-jspm-typescript

JavaScript
6
star
63

vim-markdown-writer

Some Vim functions to make writing blog posts in Markdown easier.
Vim Script
6
star
64

introduction-to-elm-workshop

Elm
5
star
65

elm-statey

A state machine library in Elm
Elm
5
star
66

elm-json-decoding

Elm
5
star
67

rollup-plugin-import-glob

JavaScript
5
star
68

advent-of-code-2018

Elm
5
star
69

angular-router-browserify

Angular's router module to be used with browserify.
JavaScript
4
star
70

project_templater

A gem for quickly creating project structures.
Ruby
4
star
71

githubissuebrowser

Browse all issues across your repositories to find something to work on.
Ruby
4
star
72

ecmascript-evaluator

JavaScript
4
star
73

JS-Instagram-Wrapper

JavaScript
4
star
74

HTML5-Placeholder-PolyFill

Adds placeholder functionality to input fields in browsers that don't support HTML5 Placeholders
JavaScript
4
star
75

london-elm-018-talk

JavaScript
4
star
76

jspm-test

Browser test runner for jspm projects
JavaScript
4
star
77

elm-console-log

An easier log function for Elm.
Elm
4
star
78

react-webpack-boilerplate

JavaScript
4
star
79

testing-javascript-workshop

JavaScript
3
star
80

elm-connect-four

Connect 4 written in Elm
Elm
3
star
81

jQuote

3
star
82

epic-fel-es6-today-links

3
star
83

devcastin

Ruby
3
star
84

beginning-react

HTML
3
star
85

jack-sublime-snippets

3
star
86

jQuery-Split-List

Splits lists in half
JavaScript
3
star
87

Base-Template

A starting point for all my development.
JavaScript
3
star
88

reactjs-workshop

Code and notes for a ReactJS workshop
JavaScript
3
star
89

Deck.js---Gamepad-API

Deck.js slideshows controlled with the Gamepad API
JavaScript
3
star
90

jsFrame

Combining a jQuery Plugin with a CSS Grid for lovely coding.
JavaScript
3
star
91

MarkdownTwitter

Automatically linking Twitter mentions in Markdown blog posts
Ruby
2
star
92

jackfranklindotcodotuk

JavaScript
2
star
93

frontendlondonfeb2015-jspm-demo

JavaScript
2
star
94

CoffeePubSub

A very small Pub/Sub implementation in CoffeeScript
CoffeeScript
2
star
95

Back-to-Top-Firefox-Plugin

An easy way to get back to the top of any webpage in Firefox.
JavaScript
2
star
96

util-fns

JavaScript
2
star
97

interactive-react

JavaScript
2
star
98

rash

Ruby hash methods in JavaScript
JavaScript
2
star
99

Big-M-Workshop-Notes

2
star
100

langtons-ant-elm

It's an ant innit.
Elm
2
star