'UseEffect API Request not displaying on page load
Apologies in advance if similar questions like this have already been answered. I have tried everything, but still cannot figure out why I am experiencing this small bug. I want this collection of tweets from my Firestore to render on the page when it loads. Right now, it only happens after I make a post request.
This is my request
useEffect(() => {
const getTweets = async () => {
const tweets = await firestore.collection('tweet').get();
tweets.forEach(doc => {
results.push(doc.data());
})
}
getTweets()
}, [])
This is where I'm mapping it to the page:
return (
<>
<main className="tweet-container">
<div className="tweet-container--content">
{results.map((tweet, index) => (
<InputResults
key={index}
tweet={tweet}
/>
))}
</div>
</main>
</>
)
}
Thank you so much
Solution 1:[1]
Try something like this,
import React, {useState, useEffect} from "react";
function App() {
const [results, setResults] = useState([]);
useEffect(() => {
const getTweets = async () => {
const tweetsData = [];
const tweets = await firestore.collection('tweet').get();
tweets.forEach(doc => {
tweetsData.push(doc.data());
})
setResults(tweetsData);
}
getTweets()
}, [])
return (
<>
<main className="tweet-container">
<div className="tweet-container--content">
{results.map((tweet, index) => (
<h1>{tweet}</h1>
))}
</div>
</main>
</>
)
}
Reference: https://reactjs.org/docs/hooks-state.html
Solution 2:[2]
Always add a key property to the elements when used a map function to show them on UI . As it would help react to differentiate between the elements .
return (
<>
<main className="tweet-container">
<div className="tweet-container--content">
{results.map((tweet, index) => (
<h1 key={index} >{tweet}</h1>
))}
</div>
</main>
</>
)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Shri Hari L |
Solution 2 | Hritik Sharma |