Skip to content

Instantly share code, notes, and snippets.

@YBCS
Created July 20, 2020 14:49
Show Gist options
  • Save YBCS/56528a845f783f29fcf2d7668bc45ba3 to your computer and use it in GitHub Desktop.
Save YBCS/56528a845f783f29fcf2d7668bc45ba3 to your computer and use it in GitHub Desktop.
part5 ex8 weird like update
//src/App.js
const newLike = async (blogObject) => {
// here
try {
const returnedBlog = await blogService.update(
blogObject.id,
blogObject.body
)
setBlogs(
blogs.map((blog) => (blog.id !== returnedBlog.id ? blog : returnedBlog))
)
} catch (exception) {
console.log(exception)
}
}
const blogForm = () => {
const hideWhenVisible = { display: blogFormVisible ? "none" : "" }
const showWhenVisible = { display: blogFormVisible ? "" : "none" }
return (
<div>
<div style={hideWhenVisible}>
<button onClick={() => setBlogFormVisible(true)}>
create new blog
</button>
{blogsSorted.map((blog) => (
// Like is updated here
<Blog key={blog.id} blog={blog} updateLike={newLike} />
))}
</div>
<div style={showWhenVisible}>
<BlogForm createBlog={addBlog} />
<div>
<button onClick={() => setBlogFormVisible(false)}>cancel</button>
</div>
</div>
</div>
)
}
//components/Blog.js
const newLike = (event) => {
event.preventDefault()
// update is sent here -- likes incremented by 1
updateLike({
id : blog.id,
body : {
user: blog.user.id,
likes: blog.likes + 1,
author: blog.author,
title: blog.title,
url: blog.url
}
})
}
// rendered here
return (
<div style={blogStyle}>
<div>
{blog.title} {blog.author}
<button onClick={toggleView}> {visible ? "hide" : "show"} </button>
</div>
<div style={showWhenVisible}>
<div>{blog.url}</div>
<div>
{blog.likes}
<button onClick={newLike}>like</button>
</div>
// this does not render once I press like
<div>{blog.user.name}</div>
</div>
</div>
)
//services/blogs.js
const update = async (id, newObject) => {
const response = await axios.put(`${baseUrl}/${id}`, newObject)
return response.data
}
// this is blogService.update
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment