Search code examples
javascriptreactjsreduxecmascript-6redux-middleware

react redux middleware cannot access variable defined in utils


Hi I created a redux custom middleware and trying to call apiUrl contstant value defined and exported from ./utils/api.js file. but getting this error

ReferenceError: Cannot access 'apiUrl' before initialization

  1. .utils/api.js file
    export const apiUrl = window.apiUrl || `${window.location.origin}/api`;
  1. redux-custom-middleware.js file
    import * as api from './config/api';
    const apiUrl = api.apiUrl;

Though, this constant value is accessible in the entire app (all components and actions) but unable to access it inside redux custom middleware.

Thanks


Solution

  • You can export a function instead of a constant, as functions are eagerly declared:

    export function apiUrl() {
        return window.apiUrl;
    }
    

    This makes it you can use apiUrl() immediately, since the circular dependency is fine since functions are "initialized" instantly.