-1

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.

1 Answer 1

-1

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>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.