简体   繁体   中英

How to add new objects to an existing useState array using map() or foreach()?

I'm trying to create a Twitter clone, and I'm having troubles with my news feed. Basically it pulls tweets from my firebase database for each user followed by the current user. So say you follow Jon Abrahams and Terry Crews, for each of these 2, it'll pull the "tweets" collection, and for each tweet, it'll return the data.

I did this with useState and useContext ( since I needed Context and couldn't make it work in a class component, but also needed state ).

  const CurrentUser = useContext(CurrentUserContext);
  const [tweets, setTweets] = useState({tweets: []});

  const feedTheFeed = async (id) => {
  const followedUsers = await getFollowedUsers(id);

  if(followedUsers) {
    followedUsers.docs.forEach(async doc => {
      const followedId = doc.data();
      const unformatTweets = await getTweetsByUser(followedId.follows);

      if(unformatTweets.docs) {
        unformatTweets.docs.map(unformatTweet => {
          const tweetText = unformatTweet.data();

          setTweets({
            tweets: [...tweets, tweetText]
          })
          // console.log(tweetText);
        })
      }
    })

    // console.log(tweets);
  }

  }

  useEffect(() => {
    if(!CurrentUser) return;

    if(CurrentUser.id || CurrentUser.uid) {
      feedTheFeed(CurrentUser.id);
    }
  }, [CurrentUser]);

The problem is that there's an issue when loading the component, it says that "tweets is not iterable", but it's an array, so I don't see why it wouldn't work. Does anyone have an idea?

Thank you !

Seems like what you want is

const [tweets, setTweets] = useState([]);

and

setTweets([...tweets, tweetText])

I think what you want to do is this.....

const [tweets, setTweets] = useState([]);

setTweets(b => [...b, tweetText])

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