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

costate

v0.0.7

Published

A state management library for react inspired by vue 3.0 reactivity api and immer

Downloads

7

Readme

Welcome to costate 👋

npm version Build Status Documentation Maintenance License: MIT Twitter: guyingjie129

A state management library for react inspired by vue 3.0 reactivity api and immer

costate is a tiny package that allows you to work with immutable state in a more reactive way.

🏠 Homepage

Features

  • mutate costate to derive the next immutable state reactively
  • write code in idiomatic javascript style
  • no need to centralize all of update-state/reducer function in React Component

Environment Requirement

  • ES2015 Proxy
  • ES0215 Map
  • ES2015 Symbol

Can I Use Proxy?

Install

npm install --save costate
yarn add costate

API DOCS

Usage

import createCostate, { watch } from 'costate'

// costate is reactive
const costate = createCostate({ a: 1 })

// state is immutable
watch(costate, state => {
  console.log(`state.a is: ${state.a}`)
})

// mutate costate will emit the next immutable state to watcher
costate.a += 1

Why costate is useful?

Think about costate + react-hooks!

Counter

import * as React from 'react'
import { co, useCostate } from 'costate'

function Counter() {
  // useCostate instead of React.useState
  // state is always immutable
  let state = useCostate({ count: 0 })

  let handleIncre = () => {
    // pass state to co, then got the costate which is reactive
    // mutate costate will cause re-render and receive the next state
    co(state).count += 1
  }

  let handleDecre = () => {
    co(state).count -= 1
  }

  return (
    <>
      <button onClick={handleIncre}>+1</button>
      {state.count}
      <button onClick={handleDecre}>-1</button>
    </>
  )
}

TodoApp

export default function App() {
  // initialize todo-app state
  let state = useCostate({
    todos: [],
    text: {
      value: ''
    }
  })

  useSessionStorage({
    key: 'todos-json',
    getter: () => state,
    setter: source => Object.assign(co(state), source)
  })

  let handleAddTodo = () => {
    if (!state.text.value) {
      return alert('empty content')
    }

    // wrap by co before mutating
    co(state).todos.push({
      id: Date.now(),
      content: state.text.value,
      completed: false
    })
    co(state).text.value = ''
  }

  let handleKeyUp = event => {
    if (event.key === 'Enter') {
      handleAddTodo()
    }
  }

  let handleToggleAll = () => {
    let hasActiveItem = state.todos.some(todo => !todo.completed)
    // wrap by co before mutating
    co(state).todos.forEach(todo => {
      todo.completed = hasActiveItem
    })
  }

  return (
    <>
      <div>
        <TodoInput text={state.text} onKeyUp={handleKeyUp} />
        <button onClick={handleAddTodo}>add</button>
        <button onClick={handleToggleAll}>toggle-all</button>
      </div>
      <Todos todos={state.todos} />
      <Footer todos={state.todos} />
    </>
  )
}

function Todos({ todos }) {
  return (
    <ul>
      {todos.map(todo => {
        return <Todo key={todo.id} todo={todo} />
      })}
    </ul>
  )
}

function Todo({ todo }) {
  // you can create any costate you want
  // be careful, costate must be object or array
  let edit = useCostate({ value: false })
  let text = useCostate({ value: '' })

  let handleEdit = () => {
    // wrap by co before mutating
    co(edit).value = !edit.value
    co(text).value = todo.content
  }

  let handleEdited = () => {
    co(edit).value = false
    // magic happen!!
    // we don't need TodoApp to pass updateTodo function down to Todo
    // we just like todo is local state, wrap by co before mutating it
    // then it will cause TodoApp drived new state and re-render
    co(todo).content = text.value
  }

  let handleKeyUp = event => {
    if (event.key === 'Enter') {
      handleEdited()
    }
  }

  let handleRemove = () => {
    // we don't need TodoApp to pass removeTodo function down to Todo
    // cotodo can be delete by remove function
    remove(co(todo))
  }

  let handleToggle = () => {
    co(todo).completed = !todo.completed
  }

  return (
    <li>
      <button onClick={handleRemove}>remove</button>
      <button onClick={handleToggle}>{todo.completed ? 'completed' : 'active'}</button>
      {edit.value && <TodoInput text={text} onBlur={handleEdited} onKeyUp={handleKeyUp} />}
      {!edit.value && <span onClick={handleEdit}>{todo.content}</span>}
    </li>
  )
}

function TodoInput({ text, ...props }) {
  let handleChange = event => {
    co(text).value = event.target.value
  }
  return <input type="text" {...props} onChange={handleChange} value={text.value} />
}

function Footer({ todos }) {
  let activeItems = todos.filter(todo => !todo.completed)
  let completedItems = todos.filter(todo => todo.completed)

  let handleClearCompleted = () => {
    ;[...completedItems].reverse().forEach(item => remove(co(item)))
  }

  return (
    <div>
      {activeItems.length} item{activeItems.length > 1 && 's'} left |{' '}
      {completedItems.length > 0 && <button onClick={handleClearCompleted}>Clear completed</button>}
    </div>
  )
}

Caveat

  • createCostate(state) only accept object or array as arguemnt

Author

👤 Jade Gu

🤝 Contributing

Contributions, issues and feature requests are welcome!

Feel free to check issues page.

Show your support

Give a ⭐️ if this project helped you!

📝 License

Copyright © 2019 Jade Gu.

This project is MIT licensed.


This README was generated with ❤️ by readme-md-generator