Home > Mobile >  Wrapping a useContext in a hook returns undefined when bundled to commonJS
Wrapping a useContext in a hook returns undefined when bundled to commonJS

Time:08-10

Problem: Code stops working when bundled. I have the following hook the consumes a context, and a component that consumes that hook:

const useAContext = () => {
  return useContext(AContext)
}
    
const SomeComponent = () => {
  const aContextProps = useAContext()
  ...
}

This works fine, no errors.

After bundling (using rollup and babel), I get the following compiled code:

var useAContext = function useAContext() {
  return useContext(AContext);
};

var SomeComponent = function SomeComponent(_ref) {
  var _useAContex = useAContext();
  ...
};

I have an App then consumes the compiled code as a library package and gives me an error saying that _useAContex is undefined. The code is being bundled to cjs and so my thought is that cjs doesn't know how to handle passing a context thru a hook. Mainly looking for an explanation to this behavior, but a workaround would also be appreciated.

CodePudding user response:

Welp, this took me hours debugging, but I found a solution. Turns out bundling wasn't the issue.

I was unknowingly trying to consume the context without first setting a provider that gave the context attributes :facepalm:

If anyone else runs into this issue, make sure you have a Context.Provider somewhere above the render tree from where you consume the context.

CodePudding user response:

I see you already found a solution, but I will post my answer anyway:

It's a common practice to throw an error if the context is undefined. It helps to debug.

const useAContext = () => {
  const context useContext(AContext)
  if (!context) {
    throw new Error('useAContext must be used inside AcontextProvider')
  }
  return context
}
  • Related