Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to upload useState and submit it to Firestore using single click

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>

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
  });
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading