purescript-react/purescript-react-basic-hooks

useContext should actuallly return not `a`, but `Maybe a`

srghma opened this issue · 3 comments

it's a usual thing to do in js

export function useData() {
  const context = useContext(DataContext)

  if (!context) {
    throw new Error('Missing Data context')
  }

  return data
}

Maybe introduce major update to the whole react-basic lib, so that all components carry additional phantom type contexts :: ContextList and top React.render should take empty context?

This is intentional. The createContext function in react-basic requires a default value and that value is used when the current React tree doesn't have a value to use from a parent provider.

createContext :: forall a. a -> Effect (ReactContext a)

If you can't provide a useful default value, you can always make your a a Maybe something.

createContext Nothing :: Effect (ReactContext (Maybe yourType))

If you're running into a runtime error here you're most likely using FFI somewhere, such as specifying in PS the context type of a JS React library. In this case it's really important JS's possible edge cases are caught or you've given the context type the actual JS type (often Nullable something, not Maybe something).

oh, sorry, I didn't think about that)

No worries, this should be documented better