On click of button, inrementation number by 1
On click of button, inrementation number by 1
Trying to make the number increment by 1 on click event,
wondering what's the right approach to this?
In my render():
{this.state.posts.map(post =>
<div key={post._id}>
<span>Votes: {post.votes}</span>
<a href="" onClick={() => this.votePost(post._id)}>
Click Me
</a>
</div>
)}
initial state:
state = {
posts: ,
};
on click function:
votePost = async id => {
await axios.put(`/posts/${id}`);
....
});
this.setState({
posts: newPostData
});
};
One more thing you can do is you can set the incremented vote on client side first then make a server call, but then you need to check if there is an error from server then you need to decrement it by 1 again on client side.
– Pawan Singh
14 mins ago
2 Answers
2
To increment a number by 1 on click you can use the following code.
constructor(){
this.state = {
count: 0
}
}
handleOnCLick = () => {
this.setState((prevState) => (count: prevState.count + 1))
}
<button onClick={thi.handleOnCLick}/>
In this case you need to decrement the vote in case there is an error form server.
– Pawan Singh
12 mins ago
If you want to change a value for a specific entry of a state array, you need to keep track of the index in your render loop :
{this.state.posts.map((post, i) =>
<div key={post._id}>
<span>Votes: {post.votes}</span>
<a href="" onClick={() => this.votePost(post._id, i)}>
Click Me
</a>
</div>
)}
So you can change the value for the right post in your votePost function
votePost = async (id, index) => {
await axios.put(`/posts/${id}`);
....
});
let {posts} = this.state
posts[index] = { ...newPostData, votes:posts[index].votes + 1 }
this.setState({posts})
}
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
where are you getting newPostData form? If you are getting it from server then its fine but you need to update that particular post only, No need to reset entire posts.
– Pawan Singh
20 mins ago