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

ts-network

v1.0.0

Published

A TypeScript datatype representing network state which taking advantage of discriminated unions(or tagged unions, algebraic data types)

Downloads

35

Readme

TypeScript Network Types

Travis Coveralls Dev Dependencies styled with prettier

A TypeScript datatype representing network state which taking advantage of discriminated unions (or tagged unions, algebraic data types).

The Problem

When representing network state, the following data structure is commonly used:

var state = {
  isFetching: true, // whether we are fetching the data
  data: [],         // the data we fetched
  error: {},        // failed to fetch the data, but got an error
}

We may raise the following questions:

  • What does it mean if isFetching === true and error field also exists? Refetching after failed? Can it mean something else?
  • What does it mean if all of the three fields exist?
  • When rendering the UI, which field should I read first?
  • How can I distinguish between initial page(not requested) and empty page(response with empty data)? by checking data === null or data.length === 0?

As we can see, it is hard to reason about by using this data structure, and it exists some impossible state.

A Solution

The above data structure is not a good model of the network state. Actually, network states are consist of:

  • haven't start the request(NotRequested)
  • the request started, and haven't get the response yet(Requesting)
  • the request succeeded, responded with some data(Succeeded)
  • the request failed, responded with error(Failed)

And in some cases, we can refresh the data:

  • refreshing by restart the request after succeeded(Refreshing)
  • refresh succeeded, got the new data(RefreshSucceeded)
  • refresh failed, got an error(RefreshFailed)

This is how this library trying to solve the problem. See the solution at the following Usage section.

Usage

import {
  NetworkState,
  getNotRequested,
  getRequesting,
  getSucceeded,
  getFailed,
} from 'ts-network'

type User = {
  id: number
  name: string
  email: string
}

type NetworkError = {
  statusCode: number
  message: number
}

type UserListRequestState = NetworkState<User[], NetworkError>

// How to set the state
function getUserListRequestState(action: Action) {
  switch (action.type) {
    case 'user-list-request-started':
      return getRequesting()
    case 'user-list-request-succeeded':
      return getSucceeded(action.response)
    case 'user-list-request-failed':
      return getFailed(action.error)
    default:
      return getNotRequested()
  }
}

// How to use the state to render UI
function render(userListRequest: UserListRequestState): UIElement {
  switch (userListRequest.kind) {
    case 'not-requested':
    // render initial page
    case 'requesting':
    // render loading page
    case 'succeeded':
    // render user list by using `userListRequest.data`
    case 'failed':
    // render error message by using `userListRequest.error`

    // TypeScript will raise an error if you misspell the case (like `case 'fialed':`).
    // You can skip the `default` case if you have already checked all the kinds.
    // And if you only check some kinds and without the `default` case, TypeScript
    // will raise an error. (You should turn on `strictNullChecks` first)
  }
}

API

See https://vincentbel.github.io/ts-network.

FAQ

Why are there no RefreshSucceeded state?

Because in common use case, after refreshing succeeded, we will rerender the UI with the new data we fetched, and turning the UI to Succeeded state waiting for another refreshing. So, using Succeeded state is enough.

If in your special case you need to store the previous data after refreshing succeeded, you should construct your own network state. like

interface RefreshSucceeded<D> {
  kind: 'refresh-succeed'
  prevData: D
  data: D
}

type MySpecialNetworkState<D, E> =
  | NotRequested
  // ...
  | RefreshingSucceeded<D>

Thanks

This library is largely inspired by the post How Elm Slays a UI Antipattern. And the talk Making Impossible States Impossible is great to watch.

License

MIT.