I want to implement valdiate method in my React-Redux app. I have a reducer which add some element to state but I need to validate that:
- This element exist in that list. If exist, app will display error (we can add element only one times)
- We can't add more that 10 (for example) element to the state.
And I will can add new validation rules into my app in the future. I create, this simple function
function addDeviceToProtocol (e) {
e.preventDefault();
if (handoverProtocol.list.find(x => x.id == device.id)) {
console.log('error')
} else {
addDevice(device);
}
}
add in my return(); block I have this
<a href="#" onClick={addDeviceToProtocol}>Add</a>
OK, it works but this code is ugly, not correctly and extend this code is not simply. I tryed use hooks like this:
function addDeviceToProtocol (e) {
e.preventDefault();
[flag, setFlag] = useState(1);
if (handoverProtocol.list.find(x => x.id == device.id)) {
setFlag(0);
console.log(error);
}
if(Flag == 1){
addDevice(device);
}
}
But I have an error:
Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
- You might have mismatching versions of React and the renderer (such as React DOM)
- You might be breaking the Rules of Hooks
- You might have more than one copy of React in the same app See url for tips about how to debug and fix this problem.
What is correctly method to validate this data like in my example?