'Apollo `useMutation()` stuck loading inside Next.js component
The following form component in Next.js submits without errors but never completes the mutation. Instead it get's stuck in the loading
state.
import React, { useState } from "react";
import { gql, useMutation } from "@apollo/client";
import { ApolloClient, InMemoryCache } from "@apollo/client";
const client = new ApolloClient({
ssrMode: true,
uri: process.env.API_URL,
cache: new InMemoryCache(),
});
const CREATE_COMMENT = gql`
mutation CreateComment(
$username: String!
$comment: String!
) {
createComment(
data: { username: $username, comment: $comment }
) {
id
username
comment
}
}
`;
export default function SocialForm() {
const [commentName, updateCommentName] = useState("");
const [commentDescription, updateCommentDescription] = useState("");
const [createComment, { data, error, loading }] = useMutation(
CREATE_COMMENT,
{ client }
);
const handleFormSubmit = async () => {
await createComment({
variables: {
name: commentName,
comment: commentDescription
},
});
};
if (loading) return "loading...";
if (error) return <p>error text :(</p>;
return (
<>
<form
onSubmit={async (e) => {
e.preventDefault();
await handleFormSubmit();
}}
className="social-form"
>
<input
required
onChange={(e) => updateCommentName(e.target.value)}
type="text"
placeholder="Full Name"
className=""
/>
<textarea
required
maxLength="280"
onChange={(e) => updateCommentDescription(e.target.value)}
className="w-full"
name="comment"
rows="5"
placeholder="Leave your thoughts and images at the moment"
/>
</form>
</>
);
}
Also the server side mutation with this exact same schema runs correctly inside Apollo playground and I'm using Keystone.js to auto generate the schema.
Solution 1:[1]
There's an error in your example:
const handleFormSubmit = async () => {
await createComment({
variables: {
name: commentName, // <-- Shouldn't this be `username: commentName,`?
comment: commentDescription
},
});
};
Otherwise, when you say the form "submits without errors but never completes", I assume you mean, from your browser? Can you see the GraphQL request being made in the browsers developer tools? I don't know which one you're in but there should be a way to see the requests being made and their responses. If the GraphQL server is returning an error, you'll see it there.
Also, what is Keystone logging on the command line during all this? If you add some console.log()
statements to your custom mutation, do they get called?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Molomby |