const favAnime = async (anime) => {
setFavani(anime.title)
setImg(anime.image_url)
setScore(anime.score)
setEpisodes(anime.episodes)
setSynopsis(anime.synopsis)
setUrl(anime.url)
const addAnime= await addDoc(collection(db,"Users", uid,"fav"),{
favani,img,score,episodes,synopsis,url
})
}
When I submit, the states updates but firebase receives empty state value, I did add the if function to upload to firebase only when state is not empty but it ended up submitting data of previous click
<div className={styles.grid}>
{data.map(function(anime){
if(data){
return <div className={styles.card}>
<img src={anime.image_url}/>
<div className={styles.wrap}>
<h1>{anime.title}</h1>
<p>Score: {anime.score}</p>
<button onClick={()=>{favAnime(anime)}}>add</button>
</div>
</div>}})}
</div>
CodePudding user response:
just add Promise of a timeout to wait until your state updates. modify your function like this
const favAnime = async (anime) => {
setFavani(anime.title)
setImg(anime.image_url)
setScore(anime.score)
setEpisodes(anime.episodes)
setSynopsis(anime.synopsis)
setUrl(anime.url)
await new Promise((resolve) => setTimeout(resolve, 350))
const addAnime= await addDoc(collection(db,"Users", uid,"fav"),{
favani,img,score,episodes,synopsis,url
})
}
or you can use data directly from anime
parameter
const favAnime = async (anime) => {
setFavani(anime.title);
setImg(anime.image_url);
setScore(anime.score);
setEpisodes(anime.episodes);
setSynopsis(anime.synopsis);
setUrl(anime.url);
const addAnime = await addDoc(collection(db, 'Users', uid, 'fav'), {
favani: anime.title,
img: anime.image_url,
score: anime.score,
episodes: anime.episodes,
synopsis: anime.synopsis,
url: anime.url
});
};