skip to Main Content

The page is redirected on form submission without going to the catch block. But, in the backend, I am getting the following error: the API body is not being executed.

Here is the page code.

"use client";
import { Button, TextField } from "@radix-ui/themes";
import SimpleMDE from "react-simplemde-editor";
import "easymde/dist/easymde.min.css";
import { useForm, Controller } from "react-hook-form";
import axios from "axios";
import { useRouter } from "next/navigation";

interface IssueInterface {
  title: string;
  description: string;
}

const NewIssue = () => {
  const router = useRouter();
  const { register, control, handleSubmit } = useForm<IssueInterface>();
  return (
    <form
      className=" max-w-xl space-y-3"
      onSubmit={handleSubmit(async (data) => {
        try {
          await axios.post("/issues/new", data);
          router.push("/issues");
        } catch (error) {
          console.log(error);
        }
      })}
    >
      <TextField.Root>
        <TextField.Input placeholder="Title" {...register("title")} />
      </TextField.Root>
      <Controller
        name="description"
        control={control}
        render={({ field }) => (
          <SimpleMDE placeholder="Description" {...field} />
        )}
      />
      <Button>Create Issue</Button>
    </form>
  );
};

export default NewIssue;

The error on the terminal

⨯ node_modules/codemirror/lib/codemirror.js (18:0) @ eval
⨯ ReferenceError: navigator is not defined
at webpack_require (/Users/krushanumohapatra/www/others/my_next_issue_tracker/.next/server/webpack-runtime.js:33:43)
at webpack_require (/Users/krushanumohapatra/www/others/my_next_issue_tracker/.next/server/webpack-runtime.js:33:43)
at webpack_require (/Users/krushanumohapatra/www/others/my_next_issue_tracker/.next/server/webpack-runtime.js:33:43)
at eval (./app/issues/new/page.tsx:9:80)
at (ssr)/./app/issues/new/page.tsx (/Users/krushanumohapatra/www/others/my_next_issue_tracker/.next/server/app/issues/new/page.js:272:1)
at webpack_require (/Users/krushanumohapatra/www/others/my_next_issue_tracker/.next/server/webpack-runtime.js:33:43)
at JSON.parse ()
null

2

Answers


  1. Seems to me that that the problem you are experiencing is a side effect by calling a function inside a components return section. Change the following line to look like this:

    onSubmit={() => {
      handleSubmit(async (data) => {
        try {
          await axios.post("/issues/new", data);
          router.push("/issues");
        } catch (error) {
          console.log(error);
        }
      });
    }};
    

    I guess the navigator is not defined error you are encountering is just the byproduct of a render loop.

    Login or Signup to reply.
  2. You’re coming from Mosh Hemdani’s course of Next.js (the practice part). I just had the same problem you mentioned and I searched for a solution, but, apparently, your problem is the only result I found. Now I’m not completely sure why this is happening, ’cause my code looks exactly like his and yours – and for him it works as it’s intended and supposed to. Perhaps it’s because he’s using an older version of Next.js 13 – while (and I’m assuming you too) I’m using the latest. Anyway. This is the way I solved the problem:

    <form
        className="space-y-3"
        onSubmit={handleSubmit(async (data) => {
            try {
                const response = await fetch("/api/issues", {
                    method: "POST",
                    headers: {
                        "Content-Type": "application/json",
                    },
                    body: JSON.stringify(data),
                });
                if (!response.ok) throw new Error();
                router.push("/issues");
            } catch (error) {
                setError("An unexpected error occurred.");
            }
        })}
    >
    

    An ok status means different codes for different requests. For a GET, indeed, 200 is the ok status code, but for a DELETE, for example, 204 would be the ok and for a POST (which we’re interested in here) 201 is the ok status code (created). You can read more about this here.

    So I’m simply checking the status code (be it ok or not) after the API returns the JSON response and then, if the status is not ok, I’m manually throwing an Error (empty as it is) that will trigger the catch portion of the try-catch block. I’m not pretty sure how the error is being triggered in Mosh’s example, though :))

    L.E.: I didn’t test with axios, for I chose to use fetch, but I guess it’s the same idea.

    L.L.E.: I just tested with axios and, apparently, there’s no need for checking the ok status. It seems like axios is already throwing an error along the way if the status is not ok. I’ll stick to fetch, however 😛

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search