Socket
Socket
Sign inDemoInstall

retil-source

Package Overview
Dependencies
9
Maintainers
1
Versions
49
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

    retil-source

Utilities to create and combine suspendable, reactive sources


Version published
Weekly downloads
4
Maintainers
1
Install size
1.43 MB
Created
Weekly downloads
 

Readme

Source

retil-source

Superpowers for React state management

NPM

Create and combine asynchronous data sources that work great with React Concurrent Mode.

Installation

# For npm users...
npm install --save retil-source

# For yarn users...
yarn add retil-source

Sources don't always have values

Why should a data source return a value before it has one?

import { createState, hasSnapshot } from 'retil'

const [stateSource, setState] = createState()
const [getState, subscribe] = stateSource

getState() // throws a promise that resolves to the first value.

setState('yo!')

getState() // now it returns 'yo!'

Examples

Say you have a source that switches between having a value, and not having a value -- e.g. because it maps an id to data on a remote server. But you still want to display the latest value.

import { Source, fuse } from 'retil'

export const fallbackToMostRecent = <T>(source: Source<T>): Source<T> => {
  let fallback: [T] | [] = []
  return fuse(use => {
    const value = use(source, ...fallback)
    fallback = [value]
    return value
  })
}

Maybe as well as remembering the most recent value, you'd also like to set a flag indicating whether the source is missing a current value. To do this, you can use your source twice, with different fallback values. Don't worry, fuse will only subscribe to the source once!

const missingFlag = Symbol('missing')

export function addBusyFlag<T, U>(
  source: Source<T>,
  build: (snapshot: T, flag: boolean) => U,
): Source<U> {
  let fallback: [T] | [] = []
  return fuse((use) => {
    const value = use(source, ...fallback)
    const valueOrFlag = use(source, missingFlag)
    fallback = [value]
    return build(value, valueOrFlag === missingFlag)
  })
}

FAQs

Last updated on 17 May 2022

Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc