Showtime
Showtime

Reputation: 99

useState don't working with array, React Hooks

    const [News, setNews] = useState([]);

    useEffect(() => {
        async function fetchData() {
            const result = await database.collection('newslatters').get();
            result.docs.forEach(doc =>
                setNews([...News, { id: doc.id, data: doc.data() }])
            );
            console.log(News); //empty array
        }
        fetchData();
    }, []);

I'm getting data from firestore, but setState it's not working, the data is coming.

Upvotes: 0

Views: 1619

Answers (1)

kyun
kyun

Reputation: 10294

Try this.

    //const [News, setNews] = useState([]); // you'd better use lowercase.
    const [news, setNews] = useState([]);
    useEffect(() => {
      async function fetchData() {
        const result = await database.collection('newslatters').get();
        /* result.docs.forEach(doc =>
          setNews([...News, {
            id: doc.id,
            data: doc.data()
          }])
        ); */
        let temp = [];
        result.docs.forEach(doc => temp.push({id: doc.id, data: doc.data() });
        setNews(temp);
        // console.log(news); //empty array
      }
      fetchData();
    }, []);

Upvotes: 2

Related Questions