Skip to content

Instantly share code, notes, and snippets.

@Idered
Created April 4, 2020 23:45
Show Gist options
  • Save Idered/e331707ff378360ff6e4926c32d952f7 to your computer and use it in GitHub Desktop.
Save Idered/e331707ff378360ff6e4926c32d952f7 to your computer and use it in GitHub Desktop.
import React from 'react'
import {nodes} from '@behavior-tree/core'
import {DevTools, createTreeStore, useTree} from '@behavior-tree/react'
const delay = (ms: number) => new Promise(resolve => setTimeout(resolve, ms))
const initialState = {
isLoggedIn: false,
isLoading: false,
profile: null,
}
const {useStore, StoreContext} = createTreeStore(initialState)
const tree = nodes.root<typeof initialState>(
nodes.selector([
nodes.sequence([
nodes.condition('Is logged in', state => state.isLoggedIn),
nodes.action('Say hello to user', state => {
console.log(`Hello ${state.profile?.name}`)
}),
]),
nodes.sequence([
nodes.action('Set is loading', state => {
state.isLoading = true
}),
nodes.action('Restore session', async state => {
await delay(2000)
state.isLoggedIn = true
state.isLoading = false
state.profile = {
name: 'Kasper',
}
}),
]),
])
)
const UserPanel = () => {
const store = useStore()
if (store.isLoading) {
return <div>Restoring session</div>
}
return (
<div>
{store.isLoggedIn ? `Hello ${store.profile?.name}` : 'Hello guest'}
</div>
)
}
const Home = () => {
const state = useTree(tree, initialState)
return (
<StoreContext.Provider value={state}>
<DevTools node={tree} />
<UserPanel />
<style jsx global>{`
body {
font-family: Roboto;
}
`}</style>
</StoreContext.Provider>
)
}
export default Home
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment