I have a function defined to fetch some data. I set default parameters like this:
JavaScript
x
4
1
export async function fetchSomeData(limit=10, offset=0) {
2
// fetch something
3
}
4
I import this function in my component and use it like so:
JavaScript
1
7
1
async componentDidMount() {
2
3
let someData = await fetchSomeData() <- This works
4
let someData = await fetchSomeData(limit=20, offset=10) <- This doesn't work
5
6
}
7
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:
JavaScript
1
2
1
let someData = await fetchSomeData(20, 10) <- This should work
2
—
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:
JavaScript
1
7
1
async componentDidMount() {
2
3
let someData = await fetchSomeData() <- This works
4
someData = await fetchSomeData(20, 10) <- This should work
5
6
}
7