Skip to content

Multiple Stores

You can easily have more than one store in your application by calling create multiple times and renaming the useAppState hook.

tsx
import { create } from '@restate/core'

const { useAppState: useUserAppState } = create({
  state: {
    name: 'John Snow',
    age: 32
  }
})

const { useAppState: useTodoAppState } = create({
  state: {
    todos: [
      { todo: 'Buy Mild', done: false },
      { todo: 'Buy Eggs', done: false }
    ]
  }
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

Example

tsx
import { create } from '@restate/core'

const { useAppState, useSelector, useNext } = create({
  state: {
    user: {
      name: 'John',
      age: 32
    }
  }
})

const { useAppState: useTodoAppState, useSelector: useTodoSelector } = create({
  state: {
    todos: [
      { id: '1', task: 'Buy milk', done: false },
      { id: '2', task: 'Buy eggs', done: true }
    ]
  }
})

function Name() {
  // We select the user name from the state
  const name = useSelector((state) => state.user.name)
  return <h1>Hello {name}!</h1>
}

function ChangeName() {
  const [name] = useAppState((state) => state.user.name)
  const next = useNext((s) => s.user.name)
  return <input value={name} onChange={(e) => next(e.target.value)} />
}

function TodoItem({ id }: { id: string }) {
  const [todo, setTodo] = useTodoAppState(
    (s) => s.todos.find((t) => t.id === id)!
  )

  return (
    <li>
      <input
        type="checkbox"
        checked={todo.done}
        onChange={(e) =>
          setTodo((todo) => {
            todo.done = e.target.checked
          })
        }
      />
      {todo.task}
    </li>
  )
}

function Todos() {
  const [todos] = useTodoAppState((s) => s.todos)

  return (
    <>
      <h1>Todos</h1>
      <ul>
        {todos.map((todo, idx) => (
          <TodoItem key={todo.id} id={todo.id} />
        ))}
      </ul>
    </>
  )
}

export function HelloStores() {
  return (
    <div className="layout">
      <Name />
      <ChangeName />
      <Todos />
    </div>
  )
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77

Full example on https://stackblitz.com/edit/hello-restate

Released under the MIT License.