react redux middleware cannot access variable defined in utils

166 views Asked by At

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

1

There are 1 answers

0
Kelvin Schoofs On BEST ANSWER

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.