Skip to content

Primitive and flexible state management for Solid based on Jotai.

License

Notifications You must be signed in to change notification settings

rtritto/solid-jotai

 
 

Repository files navigation

solid-jotai

solid-jotai

pnpm

Primitive and flexible state management for Solid based on Jotai.

Quick start

Install it:

pnpm add jotai solid-jotai

Use it:

import { atom, useAtom } from 'solid-jotai'

const countAtom = atom(0)

function Counter() {
  const [count, setCount] = useAtom(countAtom)
  return (
    <div>
      <h1>{count()}</h1>
      <button onClick={() => setCount(c => c + 1)}>one up</button>
    </div>
  )
}

Atom

An atom represents a piece of state. All you need is to specify an initial value, which can be primitive values like strings and numbers, objects and arrays. You can create as many primitive atoms as you want.

import { atom } from 'solid-jotai'

const countAtom = atom(0)
const countryAtom = atom('Japan')
const citiesAtom = atom(['Tokyo', 'Kyoto', 'Osaka'])
const mangaAtom = atom({ 'Dragon Ball': 1984, 'One Piece': 1997, 'Naruto': 1999 })

// Derived atoms
const doubledCountAtom = atom(get => get(countAtom) * 2)
const sum = atom(get => get(countAtom) + get(doubledCountAtom))

// Async atoms
const asyncAtom = atom(async () => 'hello')

Suspense

You can make the read function an async function and leverage <Suspense />:

const urlAtom = atom('https://jsonplaceholder.typicode.com/todos')
const fetchUrlAtom = atom(
  async (get) => {
    const response = await fetch(get(urlAtom))
    return await response.json()
  }
)

function TodoList() {
  const [json] = useAtom(fetchUrlAtom)
  // json is a resource so loading, status
  // and error props are available
  return <div>{JSON.stringify(json())}</div>
}

function App() {
  return (
    <Suspense fallback={<Loading />}>
      <TodoList />
    </Suspense>
  )
}

Read more about Jotai here.

License

MIT

About

Primitive and flexible state management for Solid based on Jotai.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • TypeScript 93.6%
  • CSS 4.8%
  • HTML 1.6%