简体   繁体   中英

useState is not updating state immediately

here userlist is updating immediately what can be correct code for above logic I am trying fetch userlist from firestore than traversing that list to find user details from different collection

useEffect(() => {
    db.collection("following/" + Credens.uid + "/userFollowing")
      .get()
      .then((snapshot) => {
        followingList = snapshot.docs.map((value, ind) => value.data());
      })
      .then(() => {
        if (followingList.length > 0) {
          followingList.map((value, index) => {
            db.collection("Postss")
              .doc(value.useruid)
              .collection("MovieWatched")
              .get()
              .then((snaps) => {
                // let Detail = snap.data()
                let movieidList = snaps.docs.map(
                  (value) => value.data().postMovieId
                );

                if (movieidList.includes(MovieId) === true) {
                  setuserList((prev) => [...prev, value.useruid]);
                }
              });
          });
        }
      })
      .then(() => {
        console.log(userList);
        userList.map((value, index) => {
          db.collection("users")
            .doc(value)
            .get()
            .then((snapshot) => {
              setfriendsWatchedData((prev) => [
                ...prev,
                {
                  usersID: value,
                  userData: snapshot.data(),
                },
              ]);
            });
        });
      });

    // return () => {
    //     cleanup
    // }
  }, []);

To be sure the state did change, you can use the useEffect() to monitor the changing of that state like:

useEffect(() => { 
  if (userList) {
  // userList.map....
  } 
}, [userList])

Additional conditions can be specified in the if statement. The hook will run whenever the state changes.

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