0

I am making a feature of liking and disliking a post where the data for post is coming from backend

  const blog = {
    likeStatus: false
  }
  const [liked, setLiked] = useState(blog.likeStatus);

  const likeAPI = (status) => {
    console.log(status);
  } 
  useEffect(() => {
    let status = liked ? 'LIKE' : 'DISLIKE';
    likeAPI(status); // API for liking and disliking a post
  }, [liked])
  return (
    <div className="App">
      <button style={{backgroundColor: liked ? 'green' : 'white'}}
        onClick={() => setLiked(!liked)}
      >
        Like
      </button>
    </div>
  );

This is the code for the feature

I want to run useEffect only when the like button is clicked but the useEffect also runs initially and the like status is send to the backend resulting in wrong data

Can someone help me with this ?

Any other logic is appreciated

  • You should just extract the body of useEffect to be a separate function and then call it from both useEffect and onClick. – Dean James Nov 28 '21 at 10:36
  • Does this answer your question? [Make React useEffect hook not run on initial render](https://stackoverflow.com/questions/53253940/make-react-useeffect-hook-not-run-on-initial-render) – Pradip Dhakal Nov 28 '21 at 10:37

1 Answers1

2

You do it without using a useEffect hook, like this:

const blog = {
  likeStatus: false,
};
const [liked, setLiked] = useState(blog.likeStatus);

const likeAPI = (status) => {
  console.log(status);
};

const handleClick = (liked) => {
  setLiked(liked);
  let status = liked ? "LIKE" : "DISLIKE";
  likeAPI(status); // API for liking and disliking a post
};

return (
  <div className="App">
    <button
      style={{ backgroundColor: liked ? "green" : "white" }}
      onClick={() => handleClick(!liked)}
    >
      Like
    </button>
  </div>
);
Lahcen
  • 1,231
  • 11
  • 15