Why is the context lost in the handler?

  • 0
    There is an input field, on which I hang up the 'keyup' event, after which the text of this input is added to the store. The problem is that in the addTodo function, the text value becomes empty (this can be seen from the output to the console). As a result, an empty line goes to the store.

    function Header(props) {
      const [title, setTitle] = useState('');
      const titleRef = React.createRef();
      const keyCodeEnter = 13;
    
      useEffect(() => {
        titleRef.current.addEventListener('keyup', addTodo);
        return () => titleRef.current.removeEventListener('keyup', addTodo);
      }, [])
    
      function addTodo(e) {
        console.log(title)    // ТУТ ПУСТО
        if(e.keyCode === keyCodeEnter) {
          props.addTodoCreator({
            title: title,
            isCompleted: false,
            color: 0,
          });
        }
      }
    
      return (
        <>
          <input 
            type="text" 
            value={ title } 
            onChange={ e => setTitle(e.target.value) } 
            ref={ titleRef }
          />
        </>
      );
    }


    Please help me to make the text that the user entered into the input goes to the store.
    JavaScript Grace Davila, Mar 6, 2019

  • 1 Answers
  • 0
    1. Why are you hanging the listener on the ref?

    useEffect(() => {
    titleRef.current.addEventListener('keyup', addTodo); // <-- ???
    return () => titleRef.current.removeEventListener('keyup', addTodo);
    }, [])


    2. Why would you use a snippet when you only return one element?

    return (
    <> // <-- ???
    <input
    type="text"
    value={ title }
    onChange={ e => setTitle(e.target.value) }
    ref={ titleRef }
    />
    </> // <-- ???
    );


    3. Don't use the keyCode property it is deprecated, you can use key .

    function addTodo(e) {
    if(e.keyCode === keyCodeEnter) { // <-- e.key === "Enter"
    props.addTodoCreator({
    title: title,
    isCompleted: false,
    color: 0,
    });
    }
    }




    Change your code to this one:

    const Header = ({ addTodoCreator }) => {
    const [title, setTitle] = useState("");

    const addTodo = (e) => {
    if (e.key === "Enter") {
    addTodoCreator({
    title: title,
    isCompleted: false,
    color: 0,
    });
    }
    };

    return (
    <input
    type="text"
    value={title}
    onChange={(e) => setTitle(e.target.value)}
    onKeyUp={addTodo}
    />
    );
    };
    Caroline Bowen

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!