shubham karande
shubham karande

Reputation: 21

Run useEffect only on button click

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

Upvotes: 1

Views: 6678

Answers (1)

Lahcen
Lahcen

Reputation: 1423

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>
);

Upvotes: 3

Related Questions