I am working on a social media full-stack MERNG application with Apollo GraphQL and ran into an "Invalid hook call. Hooks can only be called inside of the body of a function component." error.
This is my first time working with React and react components and I have been looking through a lot of StackOverflow posts and some documentation about the Rules of Hooks and Hooks Overview on the React documentation website but am still having some trouble trying to resolve the issue.
Here is my code:
DeleteButton.js
import React, { useState } from 'react'
import gql from 'graphql-tag'
import { useMutation } from '@apollo/react-hooks'
import { Button, Confirm, Icon } from 'semantic-ui-react'
function DeleteButton({ postID }) {
const [confirmOpen, setConfirmOpen] = useState(false)
const [deletePost] = useMutation(DELETE_POST_MUTATION, {
update() {
setConfirmOpen(false)
// TODO: Remove post from cache
},
variables: {
postID
}
})
return (
<>
<Button
as='div'
color='red'
floated='right'
onClick={() => setConfirmOpen(true)}
>
<Icon name='trash' style={{ margin: 0 }}/>
</Button>
<Confirm
open={confirmOpen}
onCancel={() => setConfirmOpen(false)}
onConfirm={deletePost}
/>
</>
)
}
const DELETE_POST_MUTATION = gql`
mutation deletePost($postID: ID!) {
deletePost(postID: $postID)
}
`
export default DeleteButton
What I'm working on here is client functionality where the user can delete their post and is met with a "setConfirmOpen(boolean)" confirmation window: "Are you sure? Yes No", when they press the delete button for the post (only if the user actually made that post).
I looked at https://reactjs.org/docs/hooks-overview.html#state-hook to help guide my intended interaction with the delete button.
I narrowed it down to onClick={() => setConfirmOpen(true)} causing my error when I click the delete button to delete the post from the database using a GraphQL mutation and am assuming that the onCancel will throw an error as well.
Thank you for your time and consideration.