Javascrip default parameter ReferenceError: param is not defined

1.1k Views Asked by At

I have a function defined to fetch some data. I set default parameters like this:

export async function fetchSomeData(limit=10, offset=0) {
    // fetch something
}

I import this function in my component and use it like so:

async componentDidMount() {
    ...
    let someData = await fetchSomeData() <- This works
    let someData = await fetchSomeData(limit=20, offset=10) <- This doesn't work
    ...
}

It works without setting limit and offset, but when I try to pass new values for offset and limit, I get an Unhandled Runtime Error ReferenceError: limit/offset is not defined. Am I missing something?

2

There are 2 best solutions below

1
On BEST ANSWER

If you call an function, you do not "set" the "parameternames".
You just simpliy parse in the Numbers/Data which you want to use inside your function.

So your function call should look like this:

let someData = await fetchSomeData(20, 10) <- This should work

--

and if you want to use the same parameter (in your case someData) again, you do not "re set" the variabletype. You simpily override the existing data.

so in your case your componentDidMount will look like this:

async componentDidMount() {
    ...
    let someData = await fetchSomeData() <- This works
    someData = await fetchSomeData(20, 10) <- This should work
    ...
}
0
On

Unlike pyhton, you don't need to specify argument names in the function.

Followings works in python,

fetchSomeData(limit=20, offset=10) 
fetchSomeData(offset=10) 

Followings are way to do same thing in JS,

fetchSomeData(20, 10) 
fetchSomeData(undefined, 10) 

If you want to use a default value for a argument pass undefined.

More Details are here