0

I tried to use generated hook from Codegen to do the signup mutation:

export default function signUpComponent() {
  const { register, handleSubmit } = useForm<SignUpFormData>();
  const [signUpMutation, { data, loading, error }] = useSignUpMutation();
  const { setToken } = useAuth();
  const onSubmit: SubmitHandler<SignUpFormData> = async (data) => {
    try {
      const result = await await signUpMutation({
        variables: {
          input: data,
        },
      });

      if (result.errors) {
        throw new Error('Cannot sign up' + result.errors);
      }
      if (result.data) {
        setToken(result.data.signUp.token);
        console.log(result.data.signUp.token);
      }
    } catch (e) {
      throw new Error(e);
    }
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <label>First Name:</label>
      <input
        className='w-1/4'
        {...register('firstName', { required: true, maxLength: 20 })}
      />
      <label>Last Name:</label>
      <input
        className='w-1/4'
        {...register('lastName', { required: true, pattern: /^[A-Za-z]+$/i })}
      />
      <label>Email:</label>
      <input
        className='w-1/4'
        {...register('email', {
          required: true,
          pattern:
            /^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/,
        })}
      />
      <label>Password:</label>
      <input
        className='w-1/4'
        {...register('password', { required: true, maxLength: 15 })}
      />
      <input type='submit' />
    </form>
  );
}

But got this error at http://localhost:3000/signup:

Unhandled Runtime Error
Error: Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.

I have tried many ways like wrapping it in useEffect or useCallback (Just follow solutions from other questions, though have no idea why), or use the async IIFE, still cannot work it out.

This is my repo: https://github.com/Jocelyn59435/Trackky_frontend

Any help is appreciated.

Housoul
  • 91
  • 1
  • 2
  • 9
  • 1
    Probably a typo, and unrelated to the issue, but you have 2 consecutive `await`s on the `signUpMutation` call. – juliomalves Sep 10 '21 at 17:45

1 Answers1

0

The error log is true, I break the hook rules, call it within a function rather than a functional component.

Under useApollo.tsx:

import { ApolloClient, HttpLink, InMemoryCache } from '@apollo/client';
import { setContext } from '@apollo/client/link/context';
import useAuth from './useAuth';

const httpLink = new HttpLink({
  uri: 'https://trackkybackend.herokuapp.com/graphql',
});

const authLink = setContext((_, { headers }) => {
  //get the authentication token from cookies

  const userToken = useAuth(); ==============> HOOK!!

  //return headers to the context so httpLink can read them
  return {
    headers: {
      ...headers,
      authorization: userToken ? `Bearer ${userToken}` : '',
    },
  };
});

export const useApollo = new ApolloClient({
  cache: new InMemoryCache(),
  link: authLink.concat(httpLink),
  ssrMode: typeof window === 'undefined',
});

Such a pain.

Housoul
  • 91
  • 1
  • 2
  • 9