7

I am trying to import a function from another module but on running am getting an error:

TypeError: _this.getData is not a function.

data.js

function getData() {
  return [
    { id: 1,
      name: 'Pluto',
      type: 'Dwarf Planet'
    },
    { id: 2,
      name: 'Neptune',
      type: 'Planet'
    }
  ]
}
export { getData }

worker.js

import getData from data.js

this.data = this.getData()

Then on run I get the browser error as mentioned above. Any ideas as to what I am doing incorrectly?

2
  • 1
    google -> "es6 import syntax" -> 1. result: MDN: import Commented Apr 1, 2017 at 14:18
  • It's getData anyway, not this. There is no this in a module scope. Commented Apr 1, 2017 at 14:29

3 Answers 3

8

That should be

import { getData } from data.js

Without the brackets, you're importing the default export which doesn't exist.

Sign up to request clarification or add additional context in comments.

Comments

6

You should omit the "this" keyword when using "getData()" it doesn't belong on the current object.

function getData() { .... }

export default getData;

import getData from "data.js"

this.data = getData();

Comments

4

Change your import as a named import like this:

import { getData } from data.js

Or export getData function as a default export like this:

export default { getData }

1 Comment

This almost worked for me but it's incomplete. You have to use the braces around the name of the imported function (import { getData } from data.js), AND you have to designate the function as an export where it's defined, if you aren't going to make it an export default. So if you aren't going to export default { getData }, you have to define it as export function getData() {...}, for instance.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.