useProductContext() returning "undefined" when used in second module

Hi all,

I am working on an application with two modules, a content action and space settings. Using forge/react@latest.

My content action will get the results from useProductContext() correctly, but when I call it in the space settings, it returns undefined. I am not using it in the resolver, so it should have access to the DOM when being called. It is imported. I tried creating a loop to wait for the results, but it never comes back with anything.

I think maybe having two modules in the Forge app might be the problem, and maybe there is something that I am missing (possibly undocumented). Is this a problem anyone has come across before?

I’ve used useProductContext in an app in multiple modules and not run across an issue like that. It’s also a hook, so should update on its own and not need any loop. Could you share more about how you’re using it?

@AaronCollier exactly, that is what i thought. It is a hook; it should have been fine.

I just have it at the top level of the function for that page’s frontend with all of the other variable definitions: const context = useProductContext() and it’s imported correctly. Nothing special or different about it. Maybe a Forge bug?

When I add it to the top line of the basic app created with forge create, I get undefined on first load and then the context after a moment in two modules (one of which is a space settings page). So it seems to be working for me, at least. Is whatever you’re using it with set up to allow undefined on first load and then a result later? Otherwise, not sure where the issue would be.

Weird, it works now for me. Guess it was some sort of odd occurrence :sweat_smile:

For any others who may stumble across this later, make sure you are using a useEffect to wait until the context is defined to continue:

useEffect(() => {
    if (context !== undefined) {
      console.log(context)
      doSomething();
    }
}, [context]);

Also, I found this out way too late, when you invoke a function, the context is automatically provided and does not need to be obtained and sent.

2 Likes

Ah yes, Forge resolvers come with the context already. Sometimes it’s not the same context, but in many cases it’s enough and you don’t need to do anything on the frontend.