I'm trying to use the useMutation
hook from react-apollo-hook
s to execute a delete mutation, but I'm having difficulty passing the ID value of the post to the mutation hook in the following code:
const Posts = () => {
const { data, error, loading } = useQuery(GET_POST)
const onDeleteHandler = useMutation(DELETE_POST, {
variables: { id }
})
if (loading) return <div>...loading</div>
if (error) return <div>Error</div>
return data.posts.map(({id, title, body, location, published, author}) => {
return (
<div className="card" key={id}>
<p>id: {id}</p>
<p>title: {title}</p>
<p>body: {body}</p>
<p>location: {location}</p>
<p>published: {published}</p>
<p>author: {author.name}</p>
<Link to={`/post/${id}/edit`}>
Edit
</Link>
<button
onClick={onDeleteHandler}>
Delete
</button>
</div>
)
})
}
I cannot include the useMutation
inside the onClick()
property since a hook cannot be used as a callback function. I tried using const inputRef = useRef()
and passing inputRef.current.value
, but kept getting undefined.
From the react-apollo-hooks
docs:
You can provide any mutation options as an argument to the useMutation hook or to the function returned by it
So you can omit the variables when calling useMutation
:
const onDeleteHandler = useMutation(DELETE_POST)
and then pass them in when calling the handler:
onClick={() => onDeleteHandler({ variables: { id } })}>
Note: react-apollo-hooks
is now deprecated since react-apollo
now supports hooks. The API is a bit different, so usage would look like this:
const [onDeleteHandler, { data, loading, error }] = useMutation(DELETE_POST)