简体   繁体   中英

Hooks Error: Next.js & Material UI Form Validation

I am trying to set up a Dialog/Modal for my users to subscribe to the newsletter. The code was fully functional when it was a normal React app, but I am converting to Next.js at the moment. Now, I am getting a RuntimeError complaining that the hooks are not configured properly. Earlier, I had issues with getting Material UI running together with next.js. but this is figured out. However I am lost here, anyone know whats happening?

My Component:

import { TextValidator, ValidatorForm } from "react-material-ui-form-validator";

import Button from "@material-ui/core/Button";
import Dialog from "@material-ui/core/Dialog";
import DialogContent from "@material-ui/core/DialogContent";
import DialogContentText from "@material-ui/core/DialogContentText";
import DialogTitle from "@material-ui/core/DialogTitle";
import { Grid } from "@material-ui/core";
import React from "react";
import Slide from "@material-ui/core/Slide";



export default function EmailPopUp() {

  const [showOpen, setShowOpen] = React.useState(true);
  const [open, setOpen] = React.useState(showOpen);
  const [form, setForm] = React.useState({
    submitted: false,
    formData: { email: "" },
  });
  const refInput = React.useRef("form");

  const isBrowser = () => typeof window !== "undefined";

  const handleClickOpen = () => setOpen(true);

  const handleClose = () => setOpen(false);



  const handleChange = (event) => {
    const { formData } = form;
    formData[event.target.name] = event.target.value;
    setForm({ formData });
  };

  const handleSubmit = () => {
    this.setForm({ submitted: true }, () => {
      formSubmitAction();
    });
  };

  const formSubmitAction = () => {
    fetch(`${process.env.NEXT_PUBLIC_BACKEND_API}subscribe_newsletter/`, {
      method: "POST",
      headers: {
        Accept: "application/json",
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        email: form.formData.email,
      }),
    }).finally(handleClose());
  };

  const Transition = React.forwardRef(function Transition(props, ref) {
    return <Slide direction="up" ref={ref} {...props} />;
  });

  return (
    isBrowser && (
      <div className="dialog-container">
        <Dialog
          disableBackdropClick={true}
          open={open}
          TransitionComponent={Transition}
          keepMounted
          onClose={handleClose}
          aria-labelledby="alert-dialog-slide-title"
          aria-describedby="alert-dialog-slide-description"
        >
          <DialogTitle id="alert-dialog-slide-title">
            Newsletter
          </DialogTitle>
          <DialogContent>
            <DialogContentText id="alert-dialog-slide-description">
              <Grid container spacing={2} justify="center">
                <Grid item xs="auto">
                  <img
                    src="/images/newsletter-img.jpg"
                    className="newsletter-image"
                  />
                </Grid>
                <Grid item xs="auto">
                  <div className="dialog-content">
              
                  </div>
                  <ValidatorForm ref={refInput} onSubmit={handleSubmit}>
                    <TextValidator
                      label="Email"
                      onChange={handleChange}
                      name="email"
                      value={form.formData.email}
                      validators={["required", "isEmail"]}
                      errorMessages={[
                        "this field is required",
                        "email is not valid",
                      ]}
                    /> 
                    <div className="newsletter-button">
                      <Button
                        type="submit"
                        variant="contained"
                        color="secondary"
                      >
                        Subscribe
                      </Button>
                    </div>
                  </ValidatorForm>
                </Grid>
              </Grid>
            </DialogContentText>
          </DialogContent>
        </Dialog>
      </div>
    )
  );
}

The stacktrace:

Unhandled Runtime 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  for tips about how to debug and fix this problem.

Call Stack
resolveDispatcher
../node_modules/react/cjs/react.development.js (1465:0)
Object.useContext
../node_modules/react/cjs/react.development.js (1473:0)
useTheme
../node_modules/@material-ui/styles/esm/useTheme/useTheme.js (4:19)
useStyles
../node_modules/@material-ui/styles/esm/makeStyles/makeStyles.js (222:24)
WithStyles
../node_modules/@material-ui/styles/esm/withStyles/withStyles.js (55:0)
renderWithHooks
node_modules/react-dom/cjs/react-dom.development.js (14803:0)
updateForwardRef
node_modules/react-dom/cjs/react-dom.development.js (16816:0)
beginWork
node_modules/react-dom/cjs/react-dom.development.js (18645:0)
HTMLUnknownElement.callCallback
node_modules/react-dom/cjs/react-dom.development.js (188:0)
Object.invokeGuardedCallbackDev
node_modules/react-dom/cjs/react-dom.development.js (237:0)
invokeGuardedCallback
node_modules/react-dom/cjs/react-dom.development.js (292:0)
beginWork$1
node_modules/react-dom/cjs/react-dom.development.js (23203:0)
performUnitOfWork
node_modules/react-dom/cjs/react-dom.development.js (22154:0)
workLoopSync
node_modules/react-dom/cjs/react-dom.development.js (22130:0)
performSyncWorkOnRoot
node_modules/react-dom/cjs/react-dom.development.js (21756:0)
eval
node_modules/react-dom/cjs/react-dom.development.js (11089:0)
unstable_runWithPriority
node_modules/scheduler/cjs/scheduler.development.js (653:0)
runWithPriority$1
node_modules/react-dom/cjs/react-dom.development.js (11039:0)
flushSyncCallbackQueueImpl
node_modules/react-dom/cjs/react-dom.development.js (11084:0)
flushSyncCallbackQueue
node_modules/react-dom/cjs/react-dom.development.js (11072:0)
flushSync
node_modules/react-dom/cjs/react-dom.development.js (21932:0)
Object.scheduleRefresh
node_modules/react-dom/cjs/react-dom.development.js (11626:0)
eval
node_modules/react-refresh/cjs/react-refresh-runtime.development.js (304:0)
Set.forEach
<anonymous>
Object.performReactRefresh
node_modules/react-refresh/cjs/react-refresh-runtime.development.js (293:0)
eval
node_modules/@next/react-refresh-utils/internal/helpers.js (124:0)

This issue is solved. After hours of researching and trying. Since I was refactoring, an react app to NextJs, I was still sharing one file with the old app from the parent directory. I move all files into the same directory and now its working. But stupid! :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM