'Clicking event increases value by two not one
I'm currently working on react state updates.
The data that I'm trying to update is a certain key-value pair in an array of objects.
When I click the thumbs-up button, the value in the 'likes' key must increase.
The problem I am facing is that the likes button will increase by 2 from the second click.
How should I handle this problem?
The code I was working on is:
import React, {useState} from 'react';
import './App.css';
function App() {
const [data, setData] = useState([{id: 0, title: '남자 코트 추천', date: '2월 17일', likes: 0}, {id: 1, title: '여자 코트 추천', date:'2월 18일', likes:0}, {id: 2, title: '강남 맛집 추천', date:'2월 19일', likes:0},]);
const handleLikesClick = (event) => {
event.stopPropagation()
setData((prevState)=>{
const updateData = [...prevState]
const id = parseInt(event.target.getAttribute("value"))
updateData[id].likes += 1;
return updateData
})
}
return (
<div className="App">
<div className="black-nav">
<div>개발 Blog</div>
</div>
{data.map(post => (
<div className="list" key={post.id}>
<h3>{post.title} <span onClick={handleLikesClick} value={post.id}>👍</span>{post.likes}</h3>
<p>{post.date}</p>
<hr/>
</div>
))}
</div>
);
}
export default App;
Solution 1:[1]
The problem was that I had Strict Mode on in index.js, which makes my component to render twice.
I omitted Strict Mode in index.js and the problem was solved.
ReactDOM.render(<App />,
document.getElementById('root')
);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | gejyn14 |
