Home > Net >  Verify if the value of input already exists in array
Verify if the value of input already exists in array

Time:10-27

i have a issue, i have two inputs then and i can't permit the user save this edit if the two values is equals.

my state who contains a data from db

const [doctorRegisters, setDoctorResgisters] = useState<any>([]);

inside this array i contain this

[{"__typename": "DoctorMedicalRegister", "counsil": "CRM", "id": "141", "isMainRegister": true, "register": "1234567/RS"}, {"__typename": "DoctorMedicalRegister", "counsil": "CRM", "id": "153", "isMainRegister": false, "register": "1234567/RS"}]

and i need compare two register who if is equal, i cant permit user save he save just is different

here is a code who i try fix this

  const isEquals = () => {
    doctorRegisters.map((item: any) => {
      if (item.register) {
        doctorRegisters.map((item2: any) => {
          if (item2.register) {
            if (item.register === item2.register) {
              console.log('iguais')
            }
          }
        });
      }
    });
  };

but this work only for dont edited values i need verify when this value is changed in input in this case i only verify in db this values is equals

here is my handle change

  const handleEditRegisterCrm = (crm: string, id: number) => {
    setDoctorResgisters(
      doctorRegisters.map((item: any) => {
        if (item && Number(item.id) == id) {
          item.register = `${crm}/${item.register?.split('/')[1] || ''}`;
        }
        return item;
      }),
    );
  };

CodePudding user response:

You could do something like:

const handleEditRegisterCrm = (crm: string, id: number) => {
  if (!doctorRegisters.some((doctorRegister) => doctorRegister.register.includes(registerToCompare)) {
    setDoctorRegisters(
      doctorRegisters.map((item: any) => {
        if (item && Number(item.id) == id) {
          item.register = `${crm}/${item.register?.split('/')[1] || ''}`;
        }
        return item;
      }),
    );
  } 
};

Remember you should keep track of the registerToCompare in order to find if it's already inserted in the doctorRegisters list. I'm assuming you can obtain that value from the your handleChange function.

  • Related