Running into a state error when attempting to change an input onChange

805 views Asked by At

I when I pass state down from a parent component the setState keeps throwing an error stating that setEmail is not a function on event change. I was wondering if there is a simple fix to this.

When I try typing in a string within the email input it throws the following error:

Error: Unhandled Runtime Error TypeError: setEmail is not a function

Parent Component: (Next.js Application)

import React, { useState, useContext, useEffect } from "react";
import "../styles/globals.css";
import "bootstrap/dist/css/bootstrap.min.css";

function MyApp({ Component, pageProps }) {
  const [tester, setTester] = useState(false);
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");

  return (
    <Component
      {...pageProps}
      email={email}
      setEmail={setEmail}
      password={password}
      setPassword={setPassword}
    />
  );
}

export default MyApp;

Child Component:

export default function Signup(props) {
  const router = useRouter();
  
  const { email, setEmail, password, setPassword, setHasAccount } = props;

// function to handle submitting a new user on click
  const onSubmit = (event) => {
    event.preventDefault();
    router.push("/questions");

  };
  return (
    <div>
      <div>
        <Container>
          <form onSubmit={onSubmit} className={styles.formSize}>
            <FormGroup>
              <Input
                className={styles.inputContainer}
                value={email}
                placeholder="[email protected]"
                onChange={(e) => setEmail(e.target.value)}
              />
              <Input
                className={styles.inputContainer}
                placeholder="password"
                value={password}
                onChange={(event) => setPassword(event.target.value)}
              />
              <Button color="primary" type="submit">
                Signup
              </Button>
              <p
                className={styles.loginPhrase}
                onClick={(event) => {
                  event.preventDefault();
                  setHasAccount(true);
                }}
              >
                Have an account? Login Here
              </p>
            </FormGroup>
          </form>
        </Container>
      </div>
      <link rel="icon" href="/favicon.ico" />
    </div>
  );
}
2

There are 2 answers

0
Rob Terrell On BEST ANSWER

I took your code and ported it over to a sandbox and it works just fine, I believe some way or another you are passing over props incorrectly. Here is a copy of the sandbox so you can see it working in action

https://codesandbox.io/s/gallant-microservice-yig2q?file=/src/App.js

0
Dave Cook On

You need to check that the parent of this component is passing in a prop called setEmail and that it is a function. It looks like maybe you've forgotten to pass it in as a prop.