2023-02-11

How to make an API request with tRPC and NextJS without an invalid hook call error

I'm trying to send user input data to my tRPC api. When I try to send my query, I get an error that I can only use React Hooks inside a function component. I believe I can't call tRPC's useQuery from a callback because it's a react hook, but how can I submit the mutation when the form is completed?

my zipcode component

'use client';

import { type NextPage } from "next"
import { NextPageButtonLink } from "../UI/NextPageButtonLink"
import { api } from "../utils/api";
import { useState } from "react";


const ZipCode: NextPage = () => {
  const [zipcode, setZipCode] = useState("");
  // This posts on every rerender and input. Ideally, it should only post when the user clicks submit
  // const postZipCodeResult = api.zipcode.postZipCode.useQuery({userId: "1", zipcode: zipcode});
  const handleSubmit = () => {
    // This throws the invalid hook location error
    const postZipCodeResult = api.zipcode.postZipCode.useQuery({userId: "1", zipcode: zipcode});

    console.log("Posting result", postZipCodeResult)
  }
  return (
    <div className="bg-[#3276AE] flex flex-col items-center h-screen">
       <form onSubmit={handleSubmit}>
        <label htmlFor="zipcode">Enter your zipcode:
        <input type="text" id="zipcode" name="zipcode" required value={zipcode} onChange={e => setZipCode(e.target.value)} />
        </label>
        <button type="submit">Submit</button>
      </form>
        <NextPageButtonLink pageName="survey" msg="Click here to start the demographics survey." />
    </div>
  )
}

export default ZipCode;

My zipcode page:

import dynamic from "next/dynamic";

const ZipCode = dynamic(() => import('../components/zipcode'), {
  ssr: false
})

export default function ZipCodePage() {
  return (<ZipCode/>)
}


my zipcode router

import { z } from "zod";

import { createTRPCRouter, publicProcedure } from "../trpc";

export const zipcodeRouter = createTRPCRouter({
  postZipCode: publicProcedure
    .input(z.object({ userId: z.string(), zipcode: z.string() }))
    .query(({ input }) => {

      return {
        zipcode: `User: ${input.userId} zipcode: ${input.zipcode}`,
      };
    }),

});


No comments:

Post a Comment