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

Time:09-20

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)

Thank you!

CodePudding user response:

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

CodePudding user response:

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