简体   繁体   中英

Wrapping a useContext in a hook returns undefined when bundled to commonJS

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.

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.

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM