Skip to content

More elegant way of checking all state values

Is there a more elegant way of checking all state variables in my react app ? I currently have 14 state variables within my app, I am checking the value of each and updating to an empty string if they do not pass validation (left empty) code is as:

  const [customerName, setCustomerName] = useState(null)
  const [customerPhone, setCustomerPhone] = useState(null)
  const [customerEmail, setCustomerEmail] = useState(null)
  const [customerAddress, setCustomerAddress] = useState(null)
  const [customerPostal, setCustomerPostal] = useState(null)
  const [purchasePrice, setPurchasePrice] = useState(null)
  const [colleagueName, setColleagueName] = useState(null)
  const [branch, setBranch] = useState(null)
  const [branchPhone, setBranchPhone] = useState(null)
  const [otherCompany, setOtherCompany] = useState(null)
  const [furtherInformation, setFurtherInformation] = useState(null)

 function submission() {
    if (customerName === null) {
        setCustomerName('')
    }
    if (customerPhone === null) {
        setCustomerPhone('')
    }
    if (customerEmail === null) {
      setCustomerEmail('')
    }
    if (customerAddress === null) {
      setCustomerAddress('')
    }
    if (customerPostal === null) {
      setCustomerPostal('')
    }
    if (purchasePrice === null) {
      setPurchasePrice('')
    }
    if (surveyType === null) {
      setSurveyType('')
    }
    if (colleagueName === null) {
      setColleagueName('')
    }
    if (branch === null) {
      setBranch('')
    }
    if (branchPhone === null) {
      setBranchPhone('')
    }
    if (company === null) {
      setCompany('')
    }
    if (company === 'Other' && otherCompany===null) {
      setCompany('Other')
      setOtherCompany('')
    }
    if (
      customerName !== ''
      && customerPhone !== ''
      && customerEmail !== ''
      && customerAddress !== ''
      && customerPostal !== ''
      && purchasePrice !== ''
      && surveyType !== ''
      && colleagueName !== ''
      && branch !== ''
      && branchPhone !== ''
      && company !== ''
      && otherCompany !== ''
    ){
      console.log('validation passed')
    }

  };

This does work, so its not the end of the world, but it just seems as though its not very elegant and I feel like there could be a more concise remedy out there?

Thanks

Answer

Maybe something along these lines. As all these state variables seem to be tightly coupled. I don’t see why they can’t be one object.

const [sale, setSale] = useState({
  customerName: '',
  customerPhone: '',
  customerEmail: '',
  customerAddress: '',
  customerPostal: '',
  purchasePrice: '',
  surveyType: '',
  colleagueName: '',
  branch: '',
  branchPhone: '',
  company: '',
  otherCompany: '',
})

const checksPasssed = Object.values(sale).every(v => v)

If you need to update one of them you can use spread.

setSale({...sale, company: 'yahoo'})