ES6 modules – imported constants undefined if not in React component

Tags: , , , ,



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

enter image description here

Answer

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


Source: stackoverflow