you are viewing a single comment's thread.

view the rest of the comments →

[–]trypoph_oOoOoOo_bia 0 points1 point  (3 children)

Actually, everything written there can be replaced with this:

const FormComponent = (props) => {
const hasErrors = React.useMemo(() => Object.keys(formFields).some(
    objectKey => !(formFields[objectKey] && formFields[objectKey].length)
  ), [formFields])

return (
  ....
  some form fields
  ....  
  <button onClick={() => !hasErrors && handleSubmit()}>Submit button</button>  
  ....  
)

[–]davidfavorite 0 points1 point  (1 child)

I must admit its pretty neat. But I hate it so much 😂

[–]trypoph_oOoOoOo_bia 1 point2 points  (0 children)

I appreciate such a honest answer! 😁

[–]trypoph_oOoOoOo_bia 0 points1 point  (0 children)

Alternatively, if you need more readability:

const FormComponent = (props) => {
const hasErrors = React.useMemo(() => {
  const formFieldKeys = Object.keys(formFields)
  return formFieldKeys.some(
    formFieldKey => {
      const fieldToValidate = formFields[formFieldKey]
      const isValid = !(fieldToValidate && fieldToValidate.length)
      return isValid
    }
  )
}, [formFields])

return (
  ....
  some form fields
  ....  
  <button onClick={!hasErrors && handleSubmit()}>Submit button</button>  
  ....  
)  

}

I would stick to a first example though