ReactJS Pass Functions through Context — TypeError: Cannot destructure property ‘…’ of ‘Object(…)(…)’ as it is undefined.

Ankur Raina
2 min readJan 9, 2021

--

Last night I spent around 3 hours trying to fix this error reading through numerous StackOverflow posts. Finally I had to sleep without fixing it. This morning I just moved a few items here and there, and voila it works. If you’re in the same situation, I hope that this blog will alleviate your pains a bit.

(The common issue which results in this error is about wrong exports/imports which is discussed a lot on StackOverflow. However, this error was not due to wrong imports. It was something different.)

Here is the app structure:

App.js

DataContext.js

HelloWorld.js

Error:

TypeError: Cannot destructure property ‘changeToPikachu’ of ‘Object(…)(…)’ as it is undefined.

Possible Reason:

I’m calling this a possible reason because I’m not an expert in ReactJS, so the conclusion I drove from this is purely based on my observation.

It seems that using both DataContextProvider and DataContext in a single file causes this issue. [Update: This didn’t turn out to be the cause. See the last section “Real reason of failure”.]

So, we will need to segregate this portion of the code.

We move the button element on Line 12 from App.js to a new JS file NameChange.js

Modified App.js is below.

Notice that the button which needed to use the function changeToPikachu from DataContext has now moved to NameChange component. Only DataContextProvider now remains in App.js.

Voila! It works.

Real reason of failure:

I wasn’t wrapping the <App/> with the <DataContextProvider> while I was trying to destructure the Context object inside the <App> component. I added this wrapping in the index.js file to resolve the issue.

By segregating the code in the files as described earlier, I was achieving the same thing without understanding what I was missing earlier.

I realised this after some brainstorming on LinkedIn. 😁

--

--

Responses (19)