Kendall
Kendall

Reputation: 5255

destructuring from module imports

I have a index.js in a folder called "vuex" with the following

const module = { state, mutations, actions, getters }

export default { module, plugin }

state, mutations, actions were imported from another file

I'm trying to get the "state" property in another file so I

import module from './veux'

then

const { state } = module

however state is undefined which is weird because console.log(module) shows me that module.state is present

I'm new to this ES6-7 flow so but what exactly am I doing wrong here?

Upvotes: 1

Views: 1432

Answers (3)

Bergi
Bergi

Reputation: 665040

I'm trying to get the "state" property in another file so I

import module from './veux'
const { state } = module

however state is undefined which is weird because console.log(module) shows me that module.state is present

No, you're importing the whole default-exported object (with its module and plugin properties) as module. The property would be module.module.state.

I have a index.js in a folder called "vuex" with the following

const module = { state, mutations, actions, getters }
export default { module, plugin }

Don't. Use named exports for exporting multiple things:

export const module = { state, mutations, actions, getters }
export { plugin }

then you can do

import { module } from './veux'
const { state } = module

Upvotes: 1

Shubham Khatri
Shubham Khatri

Reputation: 281894

Since you have exported the object {module, plugin} as default export

after importing like

import module from './veux'

module will have structure like

module = {
    module: { state, mutations, actions, getters },
    plugin
}

so in order to access state, you will write module.module.state or

const {module: {state}} = module; // nested destructuring
console.log(state)

an easier to understand and readable method would be to export your module with named export like

export const module = { state, mutations, actions, getters }

export default plugin

and import it like

import plugin, { module } from './veux'

after which you can do

const { state } = module;

Upvotes: 1

Oscar Paz
Oscar Paz

Reputation: 18312

It'll work if you do this:

import { module } from './veux';

Upvotes: -1

Related Questions