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

@livestore/livestore

v0.0.47

Published

```sh # Install deps and build libs pnpm install pnpm build

Downloads

128

Readme

Local setup

# Install deps and build libs
pnpm install
pnpm build

# Run the example app
cd examples/todomvc
pnpm dev

Caveats

  • Only supports recent browser versions (Safari 17+, ...)
  • Doesn't yet run in Next.js (easiest to use with Vite right now)

Features

  • Synchronous, transactional reads and writes
  • Otel tracing built-in

Concepts

LiveStore provides a highly structured data model for your React components. It helps you clearly reason about data dependencies, leverage the relational model and the power of SQLite, and persist UI state.

Reads

To define the data used by a component, you use the useQuery hook. There are 2 parts to defining the data:

  • local state: This is the equivalent of React.useState, but in a relational style. Each component instance gets a row in a database table to store local state. You define the schema for the table that stores this component state. In your component, you can read/write local state.
  • reactive queries: Often it's not enough to just read/write local state, you also need to query data in the global database (eg, table of todos, or table of music tracks). To do this, you can define reactive SQL or GraphQL queries. The query strings can be dynamic and depend on local state or other queries. You can also .pipe the results of any SQL or GraphQL query to do further downstream transformations.

Let's see an example. This doesn't have any local state, just queries.

We have a todos app which has a global table called app, which always has one row. It has a column called filter which has the value active, completed, or all. We want to use this value to query for only the todos which should be visible with that filter. Here's the code:

import { querySQL, sql } from '@livestore/livestore'
import { useQuery } from '@livestore/livestore/react'

const filterClause$ = querySQL<AppState[]>(`select * from app;`)
  .pipe(([appState]) => (appState.filter === 'all' ? '' : `where completed = ${appState.filter === 'completed'}`))

const visibleTodos$ = querySQL<Todo[]>((get) => sql`select * from todos ${get(filterClause$)}`)


export const MyApp: React.FC = () => {
  const visibleTodos = useQuery(visibleTodos$)

  return (
    // ...
  )
}

Writes

Writes happen through mutations: structured mutations on the LiveStore datastore. Think closer to Redux-style mutations at the domain level, rather than low-level SQL writes. This makes it clearer what's going on in the code, and enables other things like sync / undo in the future.

Write mutations can be accessed via the useLiveStoreActions hook. This is global and not component-scoped. (If you want to do a write that references some local state, you can just pass it in to the mutation arguements.)

const { store } = useStore()

// We record an event that specifies marking complete or incomplete,
// The reason is that this better captures the user's intention
// when the event gets synced across multiple devices--
// If another user toggled concurrently, we shouldn't toggle it back
const toggleTodo = (todo: Todo) =>
  store.mutate(todo.completed ? mutations.uncompleteTodo({ id: todo.id }) : mutations.completeTodo({ id: todo.id }))

Defining dependencies

LiveStore tracks which tables are read by each query and written by each mutation, in order to determine which queries need to be re-run in response to each write.

In the future we want to do this more automatically via analysis of queries, but currently this write/read table tracking is done manually. It's very important to correctly annotate write and reads with table names, otherwise reactive updates won't work correctly.

Here's how writes and reads are annotated.

Write mutations: annotate the SQL statement in the mutation definition, like this:

export const completeTodo = defineMutation(
  'completeTodo',
  Schema.struct({ id: Schema.string }),
  sql`UPDATE todos SET completed = true WHERE id = $id`,
)

GraphQL: annotate the query in the resolver, like this:

spotifyAlbum = (albumId: string) => {
  this.queriedTables.add('album_images').add('albums')

  const albums = this.db.select<AlbumSrc[]>(sql`
      select id, name,
      (
        select image_url
        from ${tableNames.album_images}
        where album_images.album_id = albums.id
        order by height desc -- use the big image for this view
        limit 1
      ) as image_url
      from albums
      where id = '${albumId}'
    `)

  return albums[0] ?? null
}

SQL: manual table annotation is not supported yet on queries, todo soon.