简体   繁体   中英

How to use a function in React useEffect

I want below code to be in React useEffect because every time things get changed I want the component to get rerender. But react does not allow useEffect in a function.

The below code is being toggled on click. Everything is working fine but the component does not reload so you need to switch between other components so that it gets updated.

const toggleFavorite = () => {
  if (docdata !== "") {
    db.collection("infodata")
      .doc(docdata)
      .set({
        favorite: !favoritePassword
      }, {
        merge: true
      });

    setFavoritePassword(!favoritePassword);
  }
};
<div onClick={toggleFavorite}>
  <FontAwesomeIcon icon={faStar} />
</div>

I have tried these: React useEffect in function React Async Function wrapped in a UseEffect

But these do not seem to work.

Any help will be appreciated,

Thank you.

you could do something like this:

const [toggle, setToggle] = useState(false);

const toggleFavorite = () => {
    if (docdata !== "") {
        db.collection("infodata")
            .doc(docdata)
            .set({
                favorite: !favoritePassword
            }, {
                merge: true
            });

        setFavoritePassword(!favoritePassword);
    }
};

useEffect(() => {
    toggleFavorite()
}, [toggle])

<div onClick={setToggle(!toggle)}>
    <FontAwesomeIcon icon={faStar} />
</div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM