pmndrs / its-fine

🐶🔥 A collection of escape hatches for React.
https://npmjs.com/its-fine
MIT License
1.05k stars 10 forks source link

feat: expose useContextMap #28

Closed hansottowirtz closed 1 year ago

hansottowirtz commented 1 year ago

Exposes useAllContexts.

This would be useful for me in @bubblydoo/angular-react, as I can use this function to inject React contexts into Angular.

See the usage of useAllContexts (I've temporarily forked its-fine) and an example of an Angular component using it and the deployed example.

CodyJasonBennett commented 1 year ago

I'm debating between this and having useContextBridge accept a context map to write into. Not sure how confusing in/out arguments are though.

hansottowirtz commented 1 year ago

Maybe we can also expose a useContextBridgeFromContexts that accepts the map?

And then

export function useContextBridge() {
  const contexts = useAllContexts()
  return useContextBridgeFromContexts(contexts)
}

Might make the api feel bloated though.

CodyJasonBennett commented 1 year ago

I think I'm happy with this PR and exposing the traversal mechanism, but maybe name it useContextMap and export type ContextMap<T = any> = Map<React.Context<T>, T> as its return type.

hansottowirtz commented 1 year ago

I'm not sure if that is the correct type, as that would imply all the possible contexts on the context map are of type T.

Unfortunately the .get method of a Map is not generic itself, because this function would make sense:

function get<K>(key: React.Context<K>): K {
  return map.get(key)
}

We could rewrite the get and keys functions in this way and expose those instead of the map to make it more type-safe, but that would probably overcomplicate it. I suggest we just keep ContextMap = Map<React.Context<any>, any>.

hansottowirtz commented 1 year ago

Just had an idea, this also works and is not too complicated.

type ContextMap = Map<React.Context<any>, any> & {
  get<T>(context: React.Context<T>): T | undefined
}
CodyJasonBennett commented 1 year ago

I see. I'm fine with whatever, just that it be exported as a type.

hansottowirtz commented 1 year ago

Alright, then I think it can be merged.