0

I got a page with some blog posts and I want users to have the ability to like/thumbs up each post and see how many likes each post has.

Right now when I like one post, all the posts get the same amount of likes. How do I only like the post I'm clicking?

Here's relevant parts of my code:


    const [posts, setPosts] = useState([])
    let [thumbsNumber, setThumbsNumber] = useState(0)

    const thumbsUp = (x) => {
        console.log('Clicked thumb: ', x)
        setThumbsNumber((thumbsNumber += 1))
    }


return (
        <div>
            {posts.map((post, index) => (
                <div key={index} style={{ marginBottom: '10px' }}>
                
                                <p style={{ float: 'right' }}>{thumbsNumber}</p>
                                <ThumbUpAltIcon
                                    className="thumbsUpBtn"
                                    onClick={() => thumbsUp(post.id)}
                                ></ThumbUpAltIcon>
                </div>
            ))}
        </div>

3 Answers 3

1

The thumbsNumber should be an object, and when setting the number, you should add/update the key (id) of the post.

Note: I'm using ?? 0 to substitute 0 if thumbsNumber[id] is not defined.

const [posts, setPosts] = useState([])
const [thumbsNumber, setThumbsNumber] = useState({})

const thumbsUp = (id) => {
  console.log('Clicked thumb: ', id)
  setThumbsNumber(thumbs => ({
    ...thumbs,
    [id]: (thumbs[id] ?? 0) + 1
  }))
}


return (
  <div>
    {posts.map((post, index) => (
    <div key={index} style={{ marginBottom: '10px' }}>
      <p style={{ float: 'right' }}>{thumbsNumber[post.id] ?? 0}</p>
      <ThumbUpAltIcon className="thumbsUpBtn" onClick={()=> thumbsUp(post.id)} >
      </ThumbUpAltIcon>
    </div>
    ))}
  </div>
)
Sign up to request clarification or add additional context in comments.

Comments

0

You must add like's number to each post for example

{
  id: 2,
  title: "name",
  ...,
  likes: 1,
}

and after that you must increase the likes number

setPosts([...posts, {this field object with new likes number}])

Comments

0

I would keep inside each post, its number of likes. for example this is post:

{id: 1 ,name: 'post1', data: 'this is post' , numberOfLikes: 0}

then update the number of likes by the id of the post.

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.