I have ratings stored in cloud firestore, and so when the page loads, I want to grab the rating (if it exists) and display it to the user. However, it does not work as intended. Although I am able to retrieve the rating from firestore, the rating value doesn't show when I refresh/load the page. Below is a snippet from the return
<div className="musicTrackInfoDiv">
<div className="musicTrackTitleAndArtist">
<label className="musicTrackTitle" style={{display: 'block'}}>{track.name}</label>
<label className="musicTrackArtist">{track.album?.artists[0].name}</label>
<ReactStars
value={Math.max(0, rating)}
count={5}
onChange={ratingChanged}
size={24}
isHalf={true}
emptyIcon={<i className="far fa-star"></i>}
halfIcon={<i className="fa fa-star-half-alt"></i>}
fullIcon={<i className="fa fa-star"></i>}
activeColor="#ffd700"
/>
</div>
</div>
In my useEffect function, I am getting the rating value from firestore and using useState hooks, I use setRating to properly set the rating value.
const [rating, setRating] = useState(0);
useEffect(() => {
db.collection("userData").doc(spotifyId).get()
.then((docSnap) => {
const songInfo = docSnap.get(id.id);
if (songInfo == undefined) {
console.log("There was no saved musicEntry");
} else {
// put the post in the text area but check if it's undefined
document.getElementById("textArea").value = songInfo.musicEntry ? songInfo.musicEntry : "";
console.log("There was a saved music entry: " songInfo.musicEntry);
// check if there is a rating
setRating(songInfo.rating ? songInfo.rating : 0);
}
})
.catch((err) => {
console.log(err);
})
}, [])
I've done a lot of testing, and yes, songInfo.rating exists as I am correctly retrieving the rating from firestore, when I console.log(songInfo.rating) it is 3, I just dont know why it doesn't show up when I render the component when the page loads.
CodePudding user response:
The issue is with the ReactStars
component. It does not react to changes to its value
prop.
A work-around for this is to provide a key
prop to force React to re-render the component when rating
changes
<ReactStars
key={`stars_${rating}`}
value={Math.max(0, rating)}
count={5}
onChange={ratingChanged}
size={24}
isHalf={true}
emptyIcon={<i className="far fa-star"></i>}
halfIcon={<i className="fa fa-star-half-alt"></i>}
fullIcon={<i className="fa fa-star"></i>}
activeColor="#ffd700"
/>
FYI this is a reported issue on the component but there is currently no official fix.