about summary refs log tree commit diff
path: root/src/state/messages/current-convo-id.tsx
blob: 082f59919dec1dd06cb8013491cc538abdf4e300 (plain) (blame)
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
import React from 'react'

const CurrentConvoIdContext = React.createContext<{
  currentConvoId: string | undefined
  setCurrentConvoId: (convoId: string | undefined) => void
}>({
  currentConvoId: undefined,
  setCurrentConvoId: () => {},
})
CurrentConvoIdContext.displayName = 'CurrentConvoIdContext'

export function useCurrentConvoId() {
  const ctx = React.useContext(CurrentConvoIdContext)
  if (!ctx) {
    throw new Error(
      'useCurrentConvoId must be used within a CurrentConvoIdProvider',
    )
  }
  return ctx
}

export function CurrentConvoIdProvider({
  children,
}: {
  children: React.ReactNode
}) {
  const [currentConvoId, setCurrentConvoId] = React.useState<
    string | undefined
  >()
  const ctx = React.useMemo(
    () => ({currentConvoId, setCurrentConvoId}),
    [currentConvoId],
  )
  return (
    <CurrentConvoIdContext.Provider value={ctx}>
      {children}
    </CurrentConvoIdContext.Provider>
  )
}