npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

remote-data-js

v0.3.0

Published

Inspired by Kris Jenkins' [RemoteData](http://package.elm-lang.org/packages/krisajenkins/elm-exts/25.1.0/Exts-RemoteData) Elm package, this library provides an object for representing remote data in your application.

Downloads

10

Readme

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