unstated-solid
v1.0.3
Published
200 bytes Solid state management libraries
Downloads
8
Readme
Unstated Solid
200 bytes Solid state management libraries
- Like
unstated-next
Install
npm install --save unstated-solid
Example
import { createSignal } from "solid-js";
import { createContainer } from "unstated-solid"
function useCounter(initialState = 0) {
let [count, setCount] = createSignal(initialState)
let decrement = () => setCount(count() - 1)
let increment = () => setCount(count() + 1)
return { count, decrement, increment }
}
let Counter = createContainer(useCounter)
function CounterDisplay() {
let counter = Counter.useContainer()
return (
<div>
<button onClick={counter.decrement}>-</button>
<span>{counter.count}</span>
<button onClick={counter.increment}>+</button>
</div>
)
}
function App() {
return (
<Counter.Provider>
<CounterDisplay />
<Counter.Provider initialState={2}>
<div>
<div>
<CounterDisplay />
</div>
</div>
</Counter.Provider>
</Counter.Provider>
)
}
render(<App />, document.getElementById("root"))
API
createContainer(useHook)
import { createContainer } from "unstated-solid"
function useCustomHook() {
let [value, setValue] = createSignal()
let onChange = e => setValue(e.currentTarget.value)
return { value, onChange }
}
let Container = createContainer(useCustomHook)
// Container === { Provider, useContainer }
<Container.Provider>
function ParentComponent() {
return (
<Container.Provider>
<ChildComponent />
</Container.Provider>
)
}
<Container.Provider initialState>
function useCustomHook(initialState = "") {
let [value, setValue] = createSignal(initialState)
// ...
}
function ParentComponent() {
return (
<Container.Provider initialState={"value"}>
<ChildComponent />
</Container.Provider>
)
}
Container.useContainer()
function ChildComponent() {
let input = Container.useContainer()
return <input value={input.value} onChange={input.onChange} />
}
useContainer(Container)
import { useContainer } from "unstated-solid"
function ChildComponent() {
let input = useContainer(Container)
return <input value={input.value} onChange={input.onChange} />
}