I have that component:
<SelectCampanha
titulo="Preenchimento obrigatório"
listaOpcoes={
category
? riskModel.filter((item) =>
item.CategoryType.includes(categoria)
)
: riskModel}
/>
Now I want to pass this filter to a function
const filter = () => {
return category
? riskModel.filter((item) =>
item.CategoryType.includes(categoria)
)
: riskModel
}
I would like to know the difference between calling an Arrow Function and a Function in a Props pass.
What is the correct way to call this function in the component?
<SelectCampanha
titulo="Preenchimento obrigatório"
listaOpcoes={filter()}
/>
or
<SelectCampanha
titulo="Preenchimento obrigatório"
listaOpcoes={() => filter()}
/>
When I used the last option, it seems that it ran the function once and there was no time to update the state of the variables
I would like to know the difference between calling an Arrow Function and a Function in a Props pass.
In Javascript a function is called when functionName() appears (note the ()). Usually you want to pass a function to your component in order to call it later on (for example as a click handler inside of the component) rather then passing the return value of a function to the component.
function myMethod() {
return 1
}
<MyComponent myPassedMethod={myMethod} myPassedValue={myMethod()} />
In the given example the props of MyComponent would be like so:
{
myPassedMethod: // function definition of "myMethod"
myPassedValue: 1 //return value of "myMethod"
}
So when you pass the filter method like so:
listaOpcoes={filter()}
you will pass the return value of filter().
If you pass it like so:
listaOpcoes={() => filter()}
a function is passed to the component props which could be called inside the component later on.
Maybe this example of two equivalent expressions does also clarify things a bit:
listaOpcoes={filter()} is equivalent to listaOpcoes={() => { return filter()}()}
Passing a function is not the same as passing its returned value.
When you pass filter(), it will get called and the returned value will be passed.
Alternatively, if you pass () => filter() it's identical to passing filter - and then you pass the actual function. This is useful when you want to decopule the calculation from the context the function is being passed in.
In your case, it seems like you want to wrap the calculation in the filter function, so you need to pass filter() as the prop - since you're using its result as the actual prop.
It depends on what your prop is expecting if you want to pass filtered items you should avoid arrow function and use
<SelectCampanha
titulo="Preenchimento obrigatório"
listaOpcoes={filter()}
/>