UseState updates late (tried useEffect, didn't work)

Viewed 33

I have a useState list and I want to update it with another list that I created like so:

//my useState
    const [friendsToSupervise, setFriendsToSupervise] = useState([{ name: "" }]);
const openMissionModal = () => {
    let supervisorsOfSelected = []
///...Adding items to "supervisorsOfSelected"...///
    setFriendsToSupervise(supervisorsOfSelected)    //trying to set state with "supervisorsOfSelected"

I tried the "useEffect" that a lot of answers mentioned all over, like this:

useEffect(() => {
    if (friendsToSupervise == { name: "" }) {

    } else {
        console.log(friendsToSupervise);
    }
}, [friendsToSupervise])

but it does not work (maybe I'm not implementing it right)

EDIT

What is happening is that I can see the previous value of "friendsToSupervise" when I press the button that activates "openMissionModal". On the one side, everything shows up, on the other, the values are not correct

Thank you!

2 Answers

Make sure openMissionModal() is called, You can test it by a console log. Or share related workflow code to get related answer.

This is not the right way of doing this.

You should never pass an array or an object as a dependency of the useEffect as they are non- primitive data-types.

Also, You can't compare objects like this.

if (friendsToSupervise == { name: "" }) 

The correct way would be:

useEffect(() => {
    if (friendsToSupervise.name==="") {

    } else {
        console.log(friendsToSupervise);
    }
}, [friendsToSupervise?.length])

Related