Home > OS >  NextJS - Unhandled Runtime Error TypeError: Cannot read properties of undefined (reading 'lengt
NextJS - Unhandled Runtime Error TypeError: Cannot read properties of undefined (reading 'lengt

Time:08-01

I'm trying to convert a class function file to hook function but am getting the following error whenever entering text in the field.

Unhandled Runtime Error TypeError: Cannot read properties of undefined (reading 'length')

I think I've converted everything but just can't find what - am I missing something?

New hooks code with the above error:

import React, { useState } from "react";

function Todo(props) {
    const [state, setState] = useState({ items: [], text: "" });

    const handleChange = (e) => {
        setState({ text: e.target.value });
    };

    const handleSubmit = (e) => {
        e.preventDefault();

        if (state.text.length === 0) {
            return;
        }

        const newItem = {
            text: state.text,
            id: Date.now(),
        };

        setState((state) => ({
            items: state.items.concat(newItem),
            text: "",
        }));
    };

    return (
        <div>
            <form onSubmit={handleSubmit}>
                <label htmlFor="new-todo">What needs to be done?</label>
                <input id="new-todo" onChange={handleChange} value={state.text} />
                <button>Add #{state.items.length   1}</button>
            </form>
            <TodoList items={state.items} />
        </div>
    );
}

function TodoList(props) {
    return (
        <ul>
            {props.items.map((item) => (
                <li key={item.id}>{item.text}</li>
            ))}
        </ul>
    );
}

export default Todo;

Previous class functions file being converted to hooks file above:

import React from "react";

class Todo extends React.Component {
    constructor(props) {
        super(props);
        this.state = { items: [], text: "" };
        this.handleChange = this.handleChange.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
    }

    render() {
        return (
            <div>
                <form onSubmit={this.handleSubmit}>
                    <label htmlFor="new-todo">What needs to be done?</label>
                    <input
                        id="new-todo"
                        onChange={this.handleChange}
                        value={this.state.text}
                    />
                    <button>Add #{this.state.items.length   1}</button>
                </form>
                <TodoList items={this.state.items} />
            </div>
        );
    }

    handleChange(e) {
        this.setState({ text: e.target.value });
    }

    handleSubmit(e) {
        e.preventDefault();
        if (this.state.text.length === 0) {
            return;
        }
        const newItem = {
            text: this.state.text,
            id: Date.now(),
        };
        this.setState((state) => ({
            items: state.items.concat(newItem),
            text: "",
        }));
    }
}

class TodoList extends React.Component {
    render() {
        return (
            <ul>
                {this.props.items.map((item) => (
                    <li key={item.id}>{item.text}</li>
                ))}
            </ul>
        );
    }
}

export default Todo;

Many thanks!

CodePudding user response:

It happens because in handleChange u rewrite whole state with { text: e.target.value } (state hook works differently than class based component state) You should try this:

const handleChange = (e) => {
    setState((prevState) => {...prevState, text: e.target.value });
};

CodePudding user response:

If I had to convert, then I would do it this way.

import React, { useState } from "react";

const Todo = () => {
  const [items, setItems] = useState([]);
  const [text, setText] = useState("");

  const handleChange = (e) => {
    setText(e.target.value);
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    if (text.length === 0) {
      return;
    }
    const newItem = {
      text,
      id: Date.now()
    };
    setItems((prevItems) => [...prevItems, newItem]);
    // clear the input box after adding.
    setText("");
  };

  return (
    <div>
      <form onSubmit={handleSubmit}>
        <label htmlFor="new-todo">What needs to be done?</label>
        <input id="new-todo" onChange={handleChange} value={text} />
        <button>Add #{items.length   1}</button>
      </form>
      <TodoList items={items} />
    </div>
  );
};

const TodoList = (props) => {
  const { items } = props;

  return (
    <ul>
      {items.map((item) => (
        <li key={item.id}>{item.text}</li>
      ))}
    </ul>
  );
};

export default Todo;

CodePudding user response:

The issue is most likely due to this block of code.

    const handleChange = (e) => {
        setState({ text: e.target.value });
        // mutating state as this will overwite the current values with
        // {text: e.target.value }
    };

a better way of doing this could be to use the rest syntax like this.

    const handleChange = (e) => {
        setState((prev) => { return {...prev, [text]: e.target.value }});
        // and now when you update text, it shouldnt overwrite your items or 
        //vice versa
    };
  • Related