 
 
 

RemoteData
Lightweight TypeScript RemoteData implementation
Install
npm install @abraham/remotedata
Usage
Read Slaying a UI Antipattern with Web Components (and TypeScript) for a more thorough guide.
This is an example class that gets a tweet (type Status) from a remote HTTP API.
import { Failure, fold, Initialized, Pending, RemoteData, Success } from '@abraham/remotedata';
import { Status } from 'twitter-d';
type State = RemoteData<number, Status>;
class Thing {
  
  private state: State = new Initialized();
  constructor() {
    
    this.getStatus();
    this.render();
  }
  private async function getStatus() {
    
    this.state = new Pending();
    
    const response = await fetch('https://api.example.com/tweet');
    if (response.ok) {
      
      const status: Status = await response.json();
      this.state = new Success(status);
    } else {
      
      this.state = new Failure(status_code);
    }
    
    this.render();
  }
  private get view(state: State): (state: State) => string {
    
    
    
    
    
    return fold<string, number, Status>(
      
      () => 'Initialized',
      
      () => 'Loading...',
      
      (error: number) => `Error: ${error}`,
      
      (status: Status) => `Got tweet from ${status.screen_name}`,
    );
  }
  private render(): string {
    
    
    const text: string = this.view(this.state);
    
  }
}
Using included type guards.
import { RemoteData } from '@abraham/remotedata';
import { Status } from 'twitter-d';
import { getState } from './state';
type State = RemoteData<number, Status>;
const state: State = getState();
if (isSuccess(state)) {
  
  console.log(state.data.full_text);
}
References