Imported function undefined on first few executions of a Reducer

Viewed 67

I'm really baffled by this odd behaviour. I'm importing a small utility function called now, which is sometimes undefined, and at other points in the execution of my application is working just as it should do.

So here is my now function:

const now = () => Date.now();

export { now };

It's super simple and designed to make mocking easier for our end to end testing. Ultimately I want to use this to set the initial state (as you can see by the commented out line below). But for debugging purposes I'm logging from my reducer:

import { now } from '../../../utils';

/**
 * {
 *     currentDate: 01/01/2020,
 * }
 */
const defaultState = {
    // currentDate: new Date(now()),
};

/**
 * Defines a Reducer to handle schedule changes
 * @param  {Object} state  The current state of the application
 * @param  {Object} action The action and payload that we want to trigger in the reducer
 * @return {Object}        The new state
 */
// eslint-disable-next-line default-param-last
const scheduleReducer = (state = defaultState, action) => {
    console.log(now);
    switch (action.type) {
        default:
            return state;
    }
};

export { scheduleReducer };

So here I'd expect now to either log as a function, or if I've got the import path wrong to be undefined (and have linting errors). This is the output I actually get:

enter image description here

I don't understand how this can be possible, when I'm trying to set it the value within initialState Jest complains that now is undefined too, so there's something really weird going on. Can anyone shed some light on this?


UPDATE

So something I didn't mention which I've deemed important is the export from the utils directory which has an index.js file that looks like this:

export * from './request';
export * from './now';

So we've managed to determine the following. If I log the full contents of the utils import, with the above import style then the import is empty:

import { now } from '../../../utils';
import * as index from '../../../utils';

console.log(index);
console.log(now);

If however I change the first import:

import { now } from '../../../utils/now';
import * as index from '../../../utils';

console.log(index);
console.log(now);

enter image description here

I don't understand why this is the case, it obviously works around my problem but I'm still interested to understand why the imports behave this way if anyone understands the reasons behind this?

On closer inspection, some of the imports had "cycles" in them, I'm guessing that this could cause a problem. I don't really know how cycles are processed/handles (or not) during imports.

0 Answers
Related