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

kr-observable

v1.0.10

Published

A proxy-based observable with a hoc for react/preact

Downloads

661

Readme

Observable

A proxy-based observer, and observable-based state-manager for react/preact.

  1. Small size – 2 kB (gzipped, non minified)
  2. Easy to use, see examples below.
  3. Supports subclasses.
  4. No dependencies.

Usage with react or preact/compat

Write a class that extends Observable, and wrap the component in observer hoc. Nothing else is needed.

import { Observable, observer } from "kr-observable";

class State extends Observable {
  results: string[] = []
  text = ''
  loading = false
  
  // All methods are automatically bounded, 
  // so you can safely use them as listeners
  setText(event: Event) {
    this.text = event.target.value
  }
  
  async search() {
    try {
      this.loading = true
      const response = await fetch('/someApi')
      this.results = await response.json()
    } catch(e) {
      console.warn(e)
    } finally {
      this.loading = false
    }
  }
  
  reset() {
    this.results = []
  }
}

const state = new State()

const Results = observer(function results() {
  // Will re-render only if the results change
  return (
    <div>
      {state.results.map(result => <div key={result}>{result}</div>)}
    </div>
  )
})

const Component = observer(function component() {
  // Will re-render only if the text or loading change
  return (
    <div>
      <input 
        placeholder="Text..." 
        onChange={state.setText}
        disabled={state.loading}
        value={state.text}
      />
      <button 
        onClick={state.search}
        disabled={state.loading}
      >
        Submit
      </button>
      
      <button onClick={state.reset}> 
        Reset
      </button>
      <Results />
    </div>
  )
})

More complicated example on CodeSandbox

Debug in react/preact

import { observer } from "kr-observable";

const Component = observer(
  function () {
    return <jsx></jsx>
  }, 
  { 
    debug: true, 
    name: 'MyComponent' // optional
  } // 
)

// will print something like that:
// "MyComponent rendered 0 times. {list of observables  that component is subscribed to}"
// "MyComponent will re-render because of changes: {list of observable values that were changed}"
// ...

Interface

type Subscriber = (property: string | symbol, value: any) => void | Promise<void>
type Listener = () => void | Promise<void>

interface Observable {
  // The callback will be triggered on each change
  listen(cb: Subscriber): void
  // remove listener
  unlisten(cb: Subscriber): void
  
  // The callback will be triggered on each "batch" 
  // i.e. some part of changes made almost at the same time,
  // for the properties passed as second argument
  subscribe(cb: Listener, keys: Set<keyof Observable>): void
  // remove subscriber
  unsubscribe(cb: Listener): void
}

Features

import { Observable } from "kr-observable";

class Example extends Observable {
  #private = 1 // ignored
  string = '' // observable
  number = 0 // observable
  array = [] // observable 
  set = new Set() // observable
  map = new Map() // observable
  plain = {
    foo: 'baz', // observable
    nestedArray: [] // observable
  } // observable
  date = new Date() // observable
  
  get something() {
    return this.number + this.string // computed 
  }
}

const example = new Example() 

const listener = (property: string | symbol, value: any) => {
  console.log(`${property} was changed, new value = `, value)
}

// will be called only once, 
// because the changes happened (almost) at the same time 
const subscriber = () => {
  console.log('subscriber was notified')
}

example.listen(listener)
example.subscribe(subscriber, new Set(['string', 'number', 'array'])) 

example.string = 'hello' // string was changed, new value = hello 
example.number = 2 // number was changed, new value = 2 
// anything that mutates an Array, Map, Set or Date is considered a change
example.array.push('string') // array was changed, new value = string 
example.array = [] // array was changed, new value = [] 
example.date.setHour(12) // date was changed, new value = 12
example.plain.foo = '' // foo was changed, new value = ''
example.plain.nestedArray.push(42) // nestedArray was changed, new value = 42