I want to increase the likes of a single blog by 1 in the incLikes function and put the updated blog back in the blogs state
const App = () => {
const [ blogs, setBlogs ] = useState(null)
useEffect(() => {
blogsService.getAll().then(initialBlogs => {
setBlogs(initialBlogs)
})
}, [])
const incLikes = blog => {
...
}
...
My mongo database contains the following blogs:
[
{
"title": "The lost planet in the milky way",
"author": "Ford Beeblebrox",
"url": "www.goldenplanet.milky.way",
"likes": 102,
"id": "600aabcbf4492017c4068727"
},
{
"title": "How the Vogols destroyed the Earth",
"author": "Michael Faraday",
"url": "www.far-far-aday.com",
"likes": 45,
"id": "600ab1575883720a04743319"
}
]
To give you a fuller context, here is how you would do it:
const [blogs, setBlogs] = React.useState(all_blogs);
const incLikes = (blog) => {
setBlogs(
blogs.map((b) => {
if (b.id === blog.id) b.likes++;
return b;
})
);
};
return (
<div className="App">
<h1>Blogs:</h1>
{blogs.map((item, i) => (
<div key={i}>
{item.title} (Likes: {item.likes}) --{" "}
<button onClick={() => incLikes(item)}> Like</button>
</div>
))}
</div>
);
So the idea is to pass a blog object into your function, then map through all the blog objects stored in the state and increment the matching one. Here is a sandbox for you.