tRPC invalid hook call in react function component

1.7k views Asked by At

I am trying to create a new user when the user connects to the site with their wallet.

When the user clicks the button to connect, the useAccount hook will return an address of type string.

I then want to create a new user with this address in my database using tRPC.

Currently, I am getting invalid hook call errors.

When a user clicks the button, the authHandler method is called which then calls this hook:

//hook to get account info
const account = useAccount();

const { connectAsync } = useConnect({
    connector: new InjectedConnector(),
    onSuccess: () => handleSuccessfulConnection(),
    onError: () => handleConnectionError(),
  });

Then the onSuccess callback executes this:

const handleSuccessfulConnection = (): void => {
    const { data } = trpc.user.createUser.useMutation(account.address);
    //runtime error here about invalid hook call
    console.log(data);
    setShowSuccessToast(true);
  };

Any way I can resolve this issue?

1

There are 1 answers

2
Christopher Ehrlich On

useMutation is a hook, so you can't call it conditionally. Once you create the mutation, you can use its mutate to fire it.

function MyComponent(props: {foo: boolean}) {
  const myMutation = trpc.router.query.useMutation();

  if (!props.foo) return null; // can't call hooks after this
  
  function handleClick() {
    myMutation.mutate(inputArgs);
  }

  return (
    <button onClick={handleClick}>Click me</button>
  )
}