Skip to content
Advertisement

Javascrip default parameter ReferenceError: param is not defined

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?

Advertisement

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
    ...
}
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement