Skip to content

Instantly share code, notes, and snippets.

@danybeltran
Last active April 14, 2023 02:09
Show Gist options
  • Save danybeltran/cbf092d79badf418c559dfd4fa63f0aa to your computer and use it in GitHub Desktop.
Save danybeltran/cbf092d79badf418c559dfd4fa63f0aa to your computer and use it in GitHub Desktop.
http-react is a data manager
import useFetch from 'http-react'
// The store. Because no url is passed, no request is sent
function useCount() {
const { data, mutate } = useFetch({
id: 'count',
default: 0
})
return [
data,
mutate,
{
increase() {
mutate(c => c + 1)
},
decrease() {
mutate(c => c - 1)
}
}
] as const // [state, setState, actions]
}
function Counter() {
// everything is statically typed!
const [count, setCount, actions] = useCount()
return (
<div>
<p>{count}</p>
<button onClick={actions.increase}>Add</button>
</div>
)
}
export default function Page() {
return (
<div>
<Counter />
<Counter />
</div>
)
}
@danybeltran
Copy link
Author

danybeltran commented Apr 8, 2023

The count state is shared in both <Counter />

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment