'ES6 modules - imported constants undefined if not in React component
The only similar question I have found is this one but I can't see how would I have caused a circular dependancy in this case:
I have a file exporting constants like so:
(choices array version is for using in Select inputs and the other one secures from typing errors in condition checks)
payments.constants.js
export const paymentMethodChoices = [
{ id: "Cash", name: "Cash" },
{ id: "BankTransfer", name: "BankTransfer" },
];
export const paymentMethods = {
Cash: paymentMethodChoices[0],
BankTransfer: paymentMethodChoices[1],
}
When they are imported inside any of my react
components all works as expected.
MyReactComponent.js
import React from 'react';
import { paymentMethods } from '../../../constants';
const defaultValues = () => {
console.log("const object is available", paymentMethods)
return {
paymentMethod: paymentMethods.Cash.id,
/* ... other scalar values*/
}
};
const MyReactComponent = (props) => { ... }
But when I try to import the constants in another js file and merge them in another constants I got an error saying they are undefined
:
defaultValues.js
import { paymentMethods } from '../../../../constants';
export const dailyCostCalendarDefaultValues = {
paymentMethod: paymentMethods.Cash.id,
vatReturn: true,
};
ERROR message: TypeError: Cannot read property 'Cash' of undefined
Solution 1:[1]
Ok, in the end it was really a circular dependancy but a really complicated one because of a long chain of files imports. Something like:
- external.js - file where the parent.js is imported
|
... - parent.js - deeply nested parent file importing fileWithProblem.js
|
-- fileWithProblem.js - importing external.js
Solution 2:[2]
sometimes the export const () => {}
is not working.
I have fixed by changing them like export function () {}
format.
After that it is working correctly but I can't understand why so.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Kia Kaha |
Solution 2 | Dream Dev |