solid-jotai
v0.3.0
Published
Primitive and flexible state management for Solid based on Jotai.
Downloads
96
Readme
solid-jotai
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