0

I have a problem with this function in React:

createContact = (item) => {
        let items = this.state.items;
        let email = this.state.email;

        if (items.length < 10 && 
            items.includes(email) === false &&
            EmailValidator.validate(email) === true) {
            this.setState(state => ({
                button: true,
                items: state.items.concat([ item ]),
                info: '✔ You have successfully added an user.'
            }))
        }
        else if (EmailValidator.validate(email) === false) {
            this.setState(state => ({
                button: true,
                items: state.items,
                info: '! User has\'t been added - the email was invalid. Try again!'
            }))
        }
        else if (items.includes(email) === true){
            this.setState(state => ({
                button: false,
                items: state.items,
                info: '! This email exists on this list.'
            }))
        }
    }    

The problem is, with this part of code items.includes(email). I used this part of code to check, if email is on list if not. But this always return 'false' - if email exist on list or not ...

I tried to use for this indexOf function - but it was the same ....

Maybe some of you will see the bug on this code or maybe my idea is not good ?

Thans for every tips and answers!

1 Answers1

1

As we could see in the image pasted in comments (why you should not doing that), you don't have an arrays of emails, you have an array of objects that includes an email in some of their properties (email).

You could use Array.prototype.some() to return true or false if some element is present passing a function as parameter items.some(o => o.email === mail) Array.prototype.includes() doesn't accept a functions as parameter.

var items = [{
    "email": "some@email.com"
  },
  {
    "email": "some@email2.com"
  },
  {
    "email": "some@email3.com"
  }
]


var mail = "some@email.com";

var mail2 = "some@email4.com";

(items.some(o => o.email === mail)) ? console.log(true): console.log(false);

(items.some(o => o.email === mail2)) ? console.log(true): console.log(false);

Finally, please read why we shouldn't paste images of code: https://meta.stackoverflow.com/a/285557/6121568

Emeeus
  • 5,072
  • 2
  • 25
  • 37