#Can't understand how to type things down the tree properly with useContext, useInterpret, useActor

1 messages · Page 1 of 1 (latest)

harsh birch
#

Hi all, I have a question surrounding global state and typescript.

// Foo.tsx
export const GlobalContext = createContext({})
export const useGlobalContext = () => useContext(GlobalContext)

function Foo(): JSX.Element() {
  const myService = useInterpret(myMachine)
  <GlobalContext.Provider value={{ myService }}>
    <Bar />
  </GlobalContext.Provider>
}

Then down in Bar.tsx:

// Bar.tsx
function Bar(): JSX.Element() {
  // ERROR: Property `myService` does not exist on type {}
  const { myService } = useGlobalContext() 
  return (
    <div>
    </div>
  )
}

So I get the error:

ERROR: Property `myService` does not exist on type {}

Thing I'm struggling with is how to type things properly here specifically in those first two lines:

export const GlobalContext = createContext({})
export const useGlobalContext = () => useContext(GlobalContext)

Can anyone help?

frozen cape
#

Have you seen createActorContext?

harsh birch
#

Hey, yes I saw this

#

@frozen cape . I understand how to make global state machines, I get the concept behind it

#

What I'm struggling on is the type definitions when I'm typing out things in the child components of the original context

#

LIke this:

// ERROR: Property `myService` does not exist on type {}
const { myService } = useGlobalContext() 
#

Which initally came from this:

const myService = useInterpret(myMachine)
frozen cape
harsh birch
#

Ah ok, I see

#

Let me check that article out some more and try it, and let you know