Search code examples
javascriptimportes6-modulesreferenceerror

Why is re-assigning imported objects throw ReferenceError?


// fileA.js

export let dataObj = {name: "intitial name"};

export let changeDataObj = () => {
 dataObj = Object.assign({}, {
      name: "changed in changeDataObj fn"
 });
}

//fileB.js
import {dataObj, changeDataObj} from "./fileA.js";

const myAsyncFunction = async () => {
   const response = await myApiCall();
   console.log(dataObj); // {name: "initial name"}
   console.log(response); // {name: "name from api"}
   dataObj = Object.assign({}, response); 
   // Throws ReferenceError: dataObj not defined on my computer with Webpack, babel
    // throws Error: "dataObj" is read-only. in codesandbox.io vanilla template using parcel. Codesandbox link https://codesandbox.io/s/nrn9o71jmm

   // but,
   changeDataObj();
   console.log(dataObj); // {name: "changed in changeDataObj fn"}
}

Why can't I re assign dataObj inside myAsyncFunction even though it is defined with let in different file but works if I call changeDataObj which is defined in the same file as dataObj. Is it the expected behavior or am I missing something ?

The link for codesandbox.io https://codesandbox.io/s/nrn9o71jmm

Please check the browser console instead of in-built codesandbox console to see errors.


Solution

  • Why can't I re assign dataObj inside myAsyncFunction even though it is defined with let in different file

    The answer is in the other error message you are getting:

    "dataObj" is read-only

    All imports are read-only. It doesn't matter how they are defined. The ReferenceError is likely due to how the code gets transformed.

    but works if I call changeDataObj which is defined in the same file as dataObj

    Because dataObj is a normal let binding in that file.