1

I have a method -

export default getLink= () => {
    const url = 'http://....'
    return url;
}

I want to use it as -

import getLink from './link';

const linkUrl= `${getLink}/food/new`;

But it seems the getLink returns me -

isfunction () {return'http://....';}/food/new

How can I return just the http link

2 Answers 2

4

You are returning a function there, since you can grab the value by invoking this function and assigning it a variable.

import getLink from './link';

const url = getLink();
const linkUrl= `${url}/food/new`;

Also, with this code actually you can't export your function like that for arrow functions. If you use default then you shouldn't use a name in your function declaration to export your function.

Instead use:

export default () => {
  const url = 'http://www.foo.com'
  return url;
};

or first assign it to a variable then use default:

 const getLink = () => {
  const url = 'http://www.foo.com'
  return url;
 };

 export default getLink;

One other alternative is using a named export instead of default.

export const getLink = () => {
  const url = 'http://www.foo.com'
  return url;
}

then import it like:

import { getLink } from "/.link";
Sign up to request clarification or add additional context in comments.

7 Comments

I believe using default export like that works just fine. Try for example to transpile it with Babel, it's valid syntax
Why shouldn't you use a local name when using a default export? I can't see a reason other than that you can't use that name twice in the file you define it in. When importing it is irrelevant if it had a name where it was defined.
@fabio.sussetto Weird, a while ago I couldn't use a name with the default export. Actually I can't use it with the Babel setup comes with CRA right now. In which stage we can use it? I can update my answer of course.
Ah: developer.mozilla.org/en-US/docs/web/javascript/reference/… It is regular functions I think. Arrow functions might be the problem and OP uses one. Though I'm still not so sure.
@trixn I was pretty sure about that but when two people argued I was somehow surprised. I've updated my answer. Now, who downvoted me, give me back my votes :D
|
3

You are not calling the function, you are concatenating the variable pointing to the function to the other string.

You should call the function to get its output instead:

const linkUrl= `${getLink()}/food/new`;

Since you're using the variable pointing to the function in a template string, the output you get is the string representation of that function (i.e. its code), obtained by calling the .toString method of the function. You can see this yourself if your try:

console.log(getLink.toString());

2 Comments

correct, I've just updated my answer in this regard, thanks.
yeah just saw that when I posted it. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.