import { useNavigate, useParams } from 'react-router-dom' import { useUserValue } from '../utils/UserContext' import { useNotification } from '../utils/NotifContext' import { postComment, putBlog, removeBlog } from '../utils/requests' import { useField, removeReset } from '../utils/hooks' import { useQuery, useQueryClient, useMutation } from 'react-query' import Loading from './Loading' import Error from './Error' import { Card, Typography, Button, Grid, TextField, List, ListItem, ListItemText, } from '@mui/material' import { ThumbUpRounded as LikeIcon, Delete as DeleteIcon, AddComment as AddCommentIcon, Create as CreateIcon, ShortText as ListIcon, } from '@mui/icons-material' const BlogView = () => { const { id } = useParams() const navigate = useNavigate() const result = useQuery('blogs') const blogs = result.data const blog = blogs !== undefined ? blogs.find(b => b.id === id) : null const user = useUserValue() const setNotif = useNotification() const comment = useField('text') const queryClient = useQueryClient() const updateBlogMutation = useMutation(putBlog, { onSuccess: () => { queryClient.invalidateQueries('blogs') }, }) // eslint-disable-next-line no-unused-vars const deleteBlogMutation = useMutation(removeBlog, { onSuccess: () => { queryClient.invalidateQueries('blogs') }, }) const addCommentMutuation = useMutation(postComment, { onSuccess: () => { queryClient.invalidateQueries('blogs') }, }) const updateBlog = async blogObj => { try { updateBlogMutation.mutateAsync(blogObj) setNotif( `Liked '${blogObj.title}' by ${blogObj.author}`, 'success', 5000 ) } catch (err) { setNotif( `Error occured while updating '${blogObj.title}'`, 'error', 5000 ) console.error(err) } } const deleteBlog = async blogObj => { try { const confirmation = window.confirm(`Delete ${blogObj.title}?`) console.log('Confirmation', confirmation) if (confirmation) { deleteBlogMutation.mutateAsync(blogObj) navigate('/') setNotif( `Deleted '${blogObj.title}' by ${blogObj.author}`, 'error', 5000 ) } else { setNotif('Deletion Cancelled', 'info', 5000) } } catch (err) { setNotif( `Error occured while Deleting '${blogObj.title}'`, 'error', 5000 ) console.log(err) } } // eslint-disable-next-line no-unused-vars const likeBlog = () => { const updatedBlog = { ...blog, likes: blog.likes + 1, } updateBlog(updatedBlog) } const delBlog = () => { deleteBlog(blog) } const addComment = () => { const commentObj = { id: blog.id, comment: comment.value, } addCommentMutuation.mutateAsync(commentObj) console.log(commentObj) comment.reset() } if (result.isLoading) return if (result.isError) return return ( {blog.title} Author: {blog.author} Link: {blog.url} Has {blog.likes} Likes   Added by {blog.user.name} {user.username === blog.user.username ? ( ) : null} Comments:   {blog.comments.length !== 0 ? ( blog.comments.map(comment => ( )) ) : ( Be the first to comment! )} ) } export default BlogView