I add a component to the page and pass the value parameter to it. before rendering, a validation function is run in the component to find the mismatch.
export default function Example({value}) {
const [error,setError] = useState(false)
let min = 5
let max = 10
validation()
function validation() {
if(value<min) return setError(true)
if(value>max) return setError(true)
}
return(
<>
<div>{value}</div>
{error && <div>ERROR</div>}
</>
)
}
I want to move the validation to a separate file. But then I have to pass all the parameters to this function. In a real project, this is a big function, with many options. This method seems to me very inconvenient and hard to maintain.
validation(min,max,value,setError)
Is there a way to separate a function without passing dozens of parameters to it?
CodePudding user response:
You can extract validation
function's logic in a separate custom hook and call it at the beginning when component code starts executing. This hook's sole responsibility would be to decide value of error
and based on validation
function's logic and return it to the component.
Refer this for more information.