• This repository has been archived on 17/Jul/2020
  • Stars
    star
    125
  • Rank 286,335 (Top 6 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 7 years ago
  • Updated over 4 years ago

Reviews

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

Repository Details

RESTful API fetching and caching for React apps, backed by an immutable state tree

npm version dependencies

Jetset

RESTful API fetching and caching for React apps, backed by an immutable state tree

Stop re-solving the problems of fetching, caching, and managing state for your RESTful API, so you can focus on your React app's unique needs.

✨ Advantages of jetset include:

  • Automatic translation of routes into intuitive methods that fetch and cache data smartly
  • Optimistic UI updates by default (with option to turn them off)
  • Zero-config for standard RESTful routes + simple overrides for non-standard routes
  • Immutable state tree guarantees no bugs from unexpected mutations
  • Time travel debugging included with jetset devtools!
  • Abstract away your API implementation details. If your api changes your code doesn't need to.
  • Server-side support (uses isomorphic-fetch behind the scenes)
  • [In progress] Use JSON schemas to express attributes of and relationships between your api models, allowing for even smarter caching, reduction of fetches, type checking, and runtime safety warnings.

This last one will provide some of the value of GraphQL + Relay without all the dependencies and complex set-up.

Install

$ npm i --save jetset

Use

Note: This README and the docs link below are for v2.x. If you are using 1.x see the 1.x docs and 1.x README

See the docs for complete documentation/reference.

To get started just specify your base url and route(s) as props on the Api component.

Quick start

import React from 'react';
import { Api } from 'jetset';

const MyApi = Component =>
  <Api url="https://my.api.com" myResource="/my_resource">
    <Component />
  </Api>

export default MyApi(({ myResource }) =>
  <div>
    { myResource.list().data.map(({ data }) =>
      <div>{ data.title }</div>
    )}
  </div>
)

More complete example:

export default MyApi(({ myResource }) =>
  <div>

    { /* GET /my_resource */ }
    { myResource.list().data.map( item => (
      <div>
        <span>{ item.data.title }</span>

        { /* PUT /my_resource/id */ }
        <button onClick={() => item.update({ title: 'renamed' }) }>Rename</button>

        { /* DELETE /my_resource/id */ }
        <button onClick={ item.delete }>Delete</button>

        { /* GET /my_resource/id */ }
        <button onClick={() => myResource.get( item.data.id ) }>Get detail</button>
      </div>
    ))}

    { /* POST /my_resource */ }
    <button onClick={() => myResource.create({ title: 'foo' }) }>Create new item</button>
  </div>
)

Example with jetset helpers

This example shows off conditional rendering based on the status of underlying fetches, and the simplicity of search/pagination using jetset.

class MyComponent extends React.Component {

  constructor() {
    super();
    this.state = {
      limit: 30,
      offset: 0
    }
  }

  onPrev = () =>
    this.setState( state => ({ offset: state.offset - state.limit }) )

  onNext = () =>
    this.setState( state => ({ offset: state.offset + state.limit }) )

  render() {
    const list = this.props.myResource.list( this.state ); // e.g. GET /my_resource?limit=30&offset=0 (cached)
    return (

      list.isPending ?
        <span>Loading...</span>
      :
      list.error ?
        <span>Error: {list.error.message}</span>
      :
      <div>
        { list.map( item => <div>{ item.data.title }</div> ) }
        <button onClick={ this.onPrev }>Prev</button>
        <button onClick={ this.onNext }>Next</button>
      </div>
    )
  }
}

Example without any React components:

You may want to take advantage of methods in action creators or elsewhere.

import { createActions } from 'jetset';

const api = createActions({ url: 'http://my.api.com', myResource: '/myResource' });

const myActionCreator = params => {
  api.myResource.create( params ).then( ... )
}

Documentation

Note: This README and the docs link below are for v2.x. If you are using 1.x see the 1.x docs and 1.x README

See the docs for complete documentation/reference.

Should I use this or Redux or both?

JetSet at its core is meant to replace all fetching, caching, and state management related to working with RESTful apis. You could use it on its own or in conjunction with a framework like Redux.

Since JetSet is backed by an immutable state tree we've created some tools that you can use to leverage that tree - globalState, localState, etc. (see examples) - but those are auxiliary, meant to be used if you're not already using a framework like Redux but you want something beyond React's component state tools, and/or you want to use time-travel debugging.

Our opinionated general guidelines are:

  • Use JetSet for an application of any size if you're working with a RESTful api.
  • If your application is nothing more than a widget just use React's state tools for the rest of your state management.
  • If your application is desktop scale but not complex, use JetSet's state tools.
  • If your application is complex you should use an actual framework like Redux. But you can still use JetSet to handle all your api interactions.

I just want direct access to my api data!

You can access it via the Jetset store, which is an Immutable.js state tree wrapped in getter/setter/subscribe methods. For example:

import { store } from 'jetset'

store.getState( '$api' )

See https://github.com/DigitalGlobe/jetset/blob/master/src/api/store.js#L6 for the shape of the API data.

To subscribe to changes:

import { store } from 'jetset'

// subscribe to all changes in api store
store.subscribeTo( '$api', newState => ... )

// subscribe to changes for just a 'users' resource
store.subscribeTo( ['$api', 'users'], newUsersState => ... )

// subscribe to changes for just a particular user model
store.subscribeTo( ['$api', 'users', 'models', '15'], newStateForUserId15 => ... )

// subscribe to changes for particular request
store.subscribeTo( ['$api', 'users', 'requests', '/foo'], newFooRequestState => ... )

Examples

  1. Clone this repo

  2. npm i

  3. npm start

  4. Go to http://localhost:8080 (or whatever port you can see assigned in the console)

Source code is available in /examples.

Test

$ npm install && npm test

More Repositories

1

mltools

A collection of Machine Learning Tools for object detection and classification on DG imagery.
Python
82
star
2

gbdxtools

(Deprecated) Python SDK for using GBDX
Python
74
star
3

geoio

Easily interact with geospatial data, particularly Digitalglobe Imagery
Python
32
star
4

tiletanic

Python library to support generalized geographic tiling schemes
Python
24
star
5

docker-logging

Log Docker containers running in AWS ECS to the ELK Stack
Shell
16
star
6

CloudServices

Cloud Services
Jupyter Notebook
16
star
7

GGD-OpenSpaceNet

General CLI for DeepCore
C++
15
star
8

gdal_ortho

Python
11
star
9

ggd-poirot

Tutorials to help students complete the Metis/DG data project #belgianjamesbond
Jupyter Notebook
11
star
10

juno-magic

IPython magics and utilities to work with bridged kernels
Python
7
star
11

tools

5
star
12

pyveda

Python api for working with veda
Python
4
star
13

standard-repo-metadata

Standard metadata files required of all DG repos, auto-scraped & validated.
Python
4
star
14

SpaceNet

3
star
15

kong-segment-log

kong proxy plugin for pushing logs to segment
Lua
3
star
16

debian-desktop

A dockerfile that builds debian jessie and the MATE desktop environment with vnc. Latest QGIS is also included.
2
star
17

timbr-machine

JavaScript
2
star
18

runscope2slack

Push runscope uptime stats to a slack channel!
Python
2
star
19

gbdxtools_notebooks

A set of helpful gbdxtools notebooks
Jupyter Notebook
2
star
20

radiant-pipeline-library

Collection of useful Jenkins library features to use across programs
Groovy
1
star
21

talavera

a python vector tiling module for vector services
Python
1
star
22

roadgan

Python
1
star
23

gbdx-caffe

Python
1
star
24

gbdxtools4j

Simple Java SDK for interacting with the GBDX system
Java
1
star
25

gbdx-s3-creds

How to get gbdx S3 credentials so you can download/upload to your GBDX S3 storage
Python
1
star
26

gbdxcli

GBDX commandline interface. Written in python, using gbdxtools.
Python
1
star
27

GGD-gbdxm

A packaging tool for importing/exporting models readable by DeepCore based applications and tools
C++
1
star
28

GISt-emailtemplate

Marketo Email Template for the GISt
HTML
1
star
29

tensorflow-docker

Shell
1
star
30

gbdx-task-StageDataToS3

The SaveToS3 task that runs in GBDX: for pushing output data to arbitrary S3 locations.
Python
1
star
31

gbdx-buffet

Python
1
star
32

GGD-ml_models_gbdx_notebooks

These are publicly available machine learning models and training data extrema for exploratory use for using gbdx notebooks
1
star
33

gbdxtools-windows-binaries

Some windows binaries helpful for gbdxtools installation
1
star