2

I've defined a function in a file but when I export and try to access the return value, I got an undefined error.

Here is my function:

export default function produits(){
  return [{nom:"chaussure",prix:45}, {nom:"polo",prix:8}]
}

When in the other file I do

import {produits} from './mesprod.js

and i don't know why i get that error. But i've just tried to change the export line of my function by removing default keyword then everything goes fine. So what is the difference between

export default function functionName()

and export function functionName()

and

export default function()

and i dont really understand the use of { } when importing a module although i use it all the time.I'm a beginner in React js

Yossi
  • 5,577
  • 7
  • 41
  • 76
Christian LSANGOLA
  • 2,947
  • 4
  • 22
  • 36
  • Possible duplicate of [When should I use curly braces for ES6 import?](https://stackoverflow.com/questions/36795819/when-should-i-use-curly-braces-for-es6-import) – Giorgi Moniava Oct 26 '18 at 06:18

2 Answers2

3

When you do export default

You should import it like

  import produits from './mesprod.js'

Because only one can be exported by default per module so it will be imported like above

When you need to use curly brackets

Say suppose you are exporting one function using default and other two without default

mesprod.js

   export default function produits (){return [{nom:"chaussure",prix:45}, {nom:"polo",prix:8}]}

   export function produits1(){return [{nom:"chaussure",prix:45}, {nom:"polo",prix:8}]}

   export function produits2(){return [{nom:"chaussure",prix:45}, {nom:"polo",prix:8}]}

So while importing you do like below

  import produits, { produits1, produits2 } from './mesprod.js'

Curly braces are used when you export multiple functions without default keyword and if you export with default then import it without curly braces

Hemadri Dasari
  • 32,666
  • 37
  • 119
  • 162
0

When you do a default export you need to remove the curly braces around the import.

Like so:

import produits from './mesprod.js'

Curly braces are used whenever you're importing a "named" export. When you do a default export you can name the default export whatever you want when you import it as such. That is, it is no longer important what the name was in the original file.

giraffesyo
  • 4,860
  • 1
  • 29
  • 39