Roger Staxx
Roger Staxx

Reputation: 439

Filter through array to find a match then execute else statement if no matches

Currently, the function executes the else statement as soon as there is no match.

I want the function to loop over all of the followers in the array first, and then, if no match exists, execute the else statement.

I have an array of followers. I want to filter through all of the followers in the array and find a match with my user value.

useEffect(() => {
    if (followers != []) {
      followers.filter((follower) => {
        if (follower.username === user) {
          setIsFollower(true);
          setUnlock(true);
          // setShowLockPage(true);
        } else {
          dispatch({
            type: "SHOW_LOCK_PAGE",
            item: {
              showLockPage: true,
            },
          });
        }
      });
    }
  }, [followers]);

Upvotes: 0

Views: 26

Answers (1)

Shimi
Shimi

Reputation: 1218

Try this one:

useEffect(() => {
    if (followers.length > 0 ) {
      const isUserExist = followers.some((follower => follower.username === user))
      if (!isUserExist){
          return dispatch({
            type: "SHOW_LOCK_PAGE",
            item: {
              showLockPage: true,
            },
          });
      }
      // executes only if (isUserExist === true)
      setIsFollower(true);
      setUnlock(true);
    }
  }, [followers]);

Upvotes: 2

Related Questions