purescript-react / purescript-react-basic-hooks

An implementation of React hooks on top of purescript-react-basic
https://pursuit.purescript.org/packages/purescript-react-basic-hooks/
Apache License 2.0
198 stars 31 forks source link

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

Closed srghma closed 3 years ago

srghma commented 3 years ago

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?

megamaddu commented 3 years ago

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).

srghma commented 3 years ago

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

megamaddu commented 2 years ago

No worries, this should be documented better