简体   繁体   中英

Form Submit Iterating for Existing Username React

I'm trying to create a sign up page where it first iterates through existing accounts and submits when input account is available; otherwise, it returns an error message if just one element matches.

I first tried.map, but it iterates through the entire array and still submits if one value is false. I then tried.find, but still produces the same result. Afterwards, I tried switch, case and could only return the proper outcome with ==. Lastly, I tried.find and.map using.includes but, again, no luck.

function handleSubmit(e) {
    e.preventDefault();
    accounts.find(acc => {
    if (acc.username.includes(formData.username)) {
        console.log("taken");
    } else {
    some post request code
}

How can I create a function that only produces one outcome if one of many elements meets the condition? Thanks for the help

You should assign the function that finds or filters the username to a variable and then create an if statement using that variable.

To return the first matching object in the array of accounts

const matchingAccount = accounts.find(account => account.username.includes(formData.username);

To return an array of matching account objects

const matchingAccounts = accounts.filter(account => account.username.includes(formData.username);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM