Reputation: 213
I have a form to add data to json using graphql and apolloq. I am using typescript with next.js\react . Getting the conflicting error about server client components. Using hook in the form component , hence "use client" is used. However when referenced from page.tsx, getting error Unhandled Runtime Error Invariant Violation: An error occurred!
export const ADD_USER = gql`
mutation AddUser($name: String!, $email: String!) {
createUser(name: $name, email: $email) {
id
name
email
}
}
`;
const UserForm: React.FC = () => {
const [name, setName] = useState('');
const [email, setEmail] = useState('');
const [addUserMutation] = useMutation(ADD_USER);
const handleSubmit = async (e: FormEvent<HTMLFormElement>) => {
e.preventDefault();
try {
await addUserMutation({
variables: {
input: {
name,
email,
},
},
});
// Optionally, clear the form fields
setName('');
setEmail('');
console.log('User added successfully!');
} catch (error) {
console.error('Error adding user:', error);
}
};
return (
<form className='userform' onSubmit={handleSubmit} >
<FormControl fullWidth margin="normal">
<InputLabel htmlFor="firstName">First Name</InputLabel >
<TextField
className='name'
name='name'
value={name}
type='text'
onChange={(e) => setName(e.target.value)}
/>
</FormControl >
<FormControl fullWidth margin="normal">
<InputLabel htmlFor="phone">Phone</InputLabel>
<TextField
className='email'
name='email'
value={email}
type='text'
onChange={(e) => setEmail(e.target.value)}
/>
</FormControl>
<FormGroup >
<Button variant="contained" type="submit">Add
</Button>
</FormGroup>
</form>
);
};
export default UserForm;
Upvotes: 1
Views: 121
Reputation: 213
I have solved it. Added apollowrapper and wrapping the layout.ts with it.
ApolloWrapper
//src/lib/apollo-wrapper.ts
"use client";
import {
ApolloClient,
ApolloLink,
HttpLink,
} from "@apollo/client";
import {
ApolloNextAppProvider,
NextSSRApolloClient,
NextSSRInMemoryCache,
SSRMultipartLink,
} from "@apollo/experimental-nextjs-app-support/ssr";
function makeClient() {
const httpLink = new HttpLink({
uri: "http://localhost:3000/api/graphql",
});
return new NextSSRApolloClient({
cache: new NextSSRInMemoryCache(),
link:
typeof window === "undefined"
? ApolloLink.from([
new SSRMultipartLink({
stripDefer: true,
}),
httpLink,
])
: httpLink,
});
}
export function ApolloWrapper({ children }: React.PropsWithChildren) {
return (
<ApolloNextAppProvider makeClient={makeClient}>
{children}
</ApolloNextAppProvider>
);
}
Layout.ts
<ApolloWrapper>
{children}
</ApolloWrapper>
Upvotes: 1