Multistep validate var

Viewed 41

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:

  1. This element exist in that list. If exist, app will display error (we can add element only one times)
  2. 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:

  1. You might have mismatching versions of React and the renderer (such as React DOM)
  2. You might be breaking the Rules of Hooks
  3. 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?

1 Answers

Hooks should be used inside a react function component

But you are using the react hook 'useState' inside a normal javascript function

This is the reason for the error.

Hooks can also be used inside a custom react hook https://reactjs.org/docs/hooks-custom.html

This error will not be thrown if you convert the javascript function into a custom react hook or a react function component

By looking at your code, useState react hook is not necessary for the code posted in question. The useState react hook is similar to state variables in a class component.

i.e. The purpose of useState react hook is to update the component when the value of the underlying state variable changes

function addDeviceToProtocol (e) {
    e.preventDefault();
    let Flag = 1;
    if (handoverProtocol.list.find(x => x.id == device.id)) {
        Flag = 0;
        console.log(error);
    }
    if(Flag == 1){
        addDevice(device);
    }
}
Related