Uncaught TypeError: Cannot read properties of undefined (reading 'length') while setting the state

Viewed 4313
Uncaught TypeError: Cannot read properties of undefined (reading 'length') 
Error is showing in react-dom-development.js file
[1]: https://i.stack.imgur.com/6a8tF.png
[2]: https://i.stack.imgur.com/Cn3EP.png

I am getting the above error whenever I am calling the method email handler of parent component from child component in order to set the state

Parent component:

const loginStates = (
    function states() {
        return {
            email: '',
            password: ''
        }
    }
)
    const LoginContainer = () => {
    const [state, setState] = useState(loginStates);

    const onChangeEmailHandler = (event) => {
        setState(prevState => {
            return { ...prevState, email: event.target.value }
        });
    }

    return (
        <div>
            <LoginComponent
                onChangeEmailHandler={onChangeEmailHandler}
            />
        </div>
    )
}

Child component:

const LoginComponent = props => {
    const classes = styles();
    const { onChangeEmailHandler } = props;
    const [isSignUpPage, setIsSignUpPage] = useState(false);

    return (
        <React.Fragment>
            <TextField 
              type='text' name='email' id='email' value={state.email}
              onChange={(event) =>onChangeEmailHandler(event)}
            />
        </React.Fragment>
    )
}
3 Answers

I have found the cause for this error, it was coming because :

<React.StrictMode>

tag was missing from index.js file, as soon as I wrap the Component with
<React.StrictMode> It started working.

//In index.js file
ReactDOM.render(
<Provider store={store}>
  <React.StrictMode>
    <App />
  </React.StrictMode>
</Provider>,
document.getElementById('root')
);

Don't pass in a function as your state, pass in the object...

const initialLoginState = {
            email: '',
            password: ''
        }
    
    const LoginContainer = () => {
    const [state, setState] = useState(initialLoginState);

I couldn't reproduce your error, however I made few changes to your code to make it work, it turns out that in order to pass a function in useState hook you need to pass a higher order function that returns the function you want, you can check full explanation here.

Parent Component:

import LoginComponent from "./child";
import React, { useState } from "react";

const loginState = function states() {
  return {
    email: "",
    password: ""
  };
};

const LoginContainer = () => {
  const [state, setState] = useState(() => loginState);

  const onChangeEmailHandler = (email) => {
    const cur = state();
    setState(() => () => ({ ...cur, email }));
  };

  return (
    <div>
      <LoginComponent
        onChangeEmailHandler={onChangeEmailHandler}
        email={state().email} // You need to pass the email here to display it on rerender.
      />
    </div>
  );
};

export default LoginContainer;

Child Component:

import React from "react";

const LoginComponent = (props) => {
  // const classes = styles();
  const { onChangeEmailHandler } = props;
  // const [isSignUpPage, setIsSignUpPage] = useState(false);

  return (
    <React.Fragment>
      <input
        type="text"
        name="email"
        id="email"
        value={props.email} // recieve the email from the props passed from parent.
        onChange={(event) => onChangeEmailHandler(event.target.value)}
      />
    </React.Fragment>
  );
};

export default LoginComponent;

You can check my sand box here

Related