Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For loop only working on second loop with React hooks

I have a project that I am going to add tags, similar to this site. I want to first check if the tag has already been selected by the user. I have a for loop to see if the tag added equals the tags that are already there.

If I make a tag named Jack, it will work just fine. If I create another tag named Jack, now I have two Jacks(not good). On the third attempt, it doesn't add another Jack (good.)

Here is my relevant code. I have added the console as well. My useState setTagAlreadyThere on is being ignored until the third attempt, when it should go to true on the second attempt. What am I doing wrong here?

const [tagsFound, setTagsFound] = useState([])
const [tagsAdded, setTagsAdded] = useState([])    
const [tagAlreadyThere, setTagAlreadyThere] = useState(false)

const gatherTags = (tags) => {
    setTagAlreadyThere(false)
    console.log(tagAlreadyThere)

    if (tagsAdded.length === 0) {
        setTagsAdded([...tagsAdded, tags]);
    } else {
        console.log(tagsAdded)

        for (let i = 0; i < tagsAdded.length; i++) {
            console.log(tagsAdded[i])

            if (tags === tagsAdded[i]) {
                console.log(tagsAdded[i])
                console.log(tags)
                setTagAlreadyThere(true)
                console.log(tagAlreadyThere)
            }
        }
        console.log(tagAlreadyThere)
        if (tagAlreadyThere === false) {
            setTagsAdded([...tagsAdded, tags]);
            console.log(tagsAdded)
        } else {
            return
        }
    }

    setPostTag('')
}

Console.

TagAdder.tsx:9 jack
postarticle.tsx:64 false
postarticle.tsx:69 ["jack"]
postarticle.tsx:72 jack
postarticle.tsx:75 jack
postarticle.tsx:76 jack
postarticle.tsx:78 false
postarticle.tsx:81 false
postarticle.tsx:84 ["jack"]
post.tsx:6 {}
postarticle.tsx:92 (2) ["jack", "jack"]
post.tsx:6 {}
postarticle.tsx:

92

like image 796
lakerskill Avatar asked Mar 12 '26 07:03

lakerskill


1 Answers

no offense but you code has so many unnecessary stuff.

So why it is happening. Because you tagAlreadyThere is not updated yet. And you are checking it is value.

const gatherTags = (tags) => {
    if (!tagsAdded.inlcudes(tags)) {
      setTagsAdded([...tagsAdded, tags]);
      setPostTag('')
    }
}

No need for const [tagAlreadyThere, setTagAlreadyThere] = useState(false)

like image 142
Talgat Saribayev Avatar answered Mar 14 '26 19:03

Talgat Saribayev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!