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:
JavaScript
x
69
69
1
const [customerName, setCustomerName] = useState(null)
2
const [customerPhone, setCustomerPhone] = useState(null)
3
const [customerEmail, setCustomerEmail] = useState(null)
4
const [customerAddress, setCustomerAddress] = useState(null)
5
const [customerPostal, setCustomerPostal] = useState(null)
6
const [purchasePrice, setPurchasePrice] = useState(null)
7
const [colleagueName, setColleagueName] = useState(null)
8
const [branch, setBranch] = useState(null)
9
const [branchPhone, setBranchPhone] = useState(null)
10
const [otherCompany, setOtherCompany] = useState(null)
11
const [furtherInformation, setFurtherInformation] = useState(null)
12
13
function submission() {
14
if (customerName === null) {
15
setCustomerName('')
16
}
17
if (customerPhone === null) {
18
setCustomerPhone('')
19
}
20
if (customerEmail === null) {
21
setCustomerEmail('')
22
}
23
if (customerAddress === null) {
24
setCustomerAddress('')
25
}
26
if (customerPostal === null) {
27
setCustomerPostal('')
28
}
29
if (purchasePrice === null) {
30
setPurchasePrice('')
31
}
32
if (surveyType === null) {
33
setSurveyType('')
34
}
35
if (colleagueName === null) {
36
setColleagueName('')
37
}
38
if (branch === null) {
39
setBranch('')
40
}
41
if (branchPhone === null) {
42
setBranchPhone('')
43
}
44
if (company === null) {
45
setCompany('')
46
}
47
if (company === 'Other' && otherCompany===null) {
48
setCompany('Other')
49
setOtherCompany('')
50
}
51
if (
52
customerName !== ''
53
&& customerPhone !== ''
54
&& customerEmail !== ''
55
&& customerAddress !== ''
56
&& customerPostal !== ''
57
&& purchasePrice !== ''
58
&& surveyType !== ''
59
&& colleagueName !== ''
60
&& branch !== ''
61
&& branchPhone !== ''
62
&& company !== ''
63
&& otherCompany !== ''
64
){
65
console.log('validation passed')
66
}
67
68
};
69
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
Advertisement
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.
JavaScript
1
17
17
1
const [sale, setSale] = useState({
2
customerName: '',
3
customerPhone: '',
4
customerEmail: '',
5
customerAddress: '',
6
customerPostal: '',
7
purchasePrice: '',
8
surveyType: '',
9
colleagueName: '',
10
branch: '',
11
branchPhone: '',
12
company: '',
13
otherCompany: '',
14
})
15
16
const checksPasssed = Object.values(sale).every(v => v)
17
If you need to update one of them you can use spread.
JavaScript
1
2
1
setSale({sale, company: 'yahoo'})
2