5

I'm beginnig my journey into TypeScript in React and to experiment what I've learn, I've try a simple Todo App. Everything is working fine except ONE things !

When I'm pushing 'newTask' When I'm hovering 'newTask' here's the hint (Google Trad from French) :

The 'Todo | undefined 'is not attributable to the parameter of type' Todo '. Cannot assign type 'undefined' to type 'Todo'.

I guess it's related to something here :

let [newTask, setNewTask] = useState<Todo>();

because if I type useState<any>(); I don't have any error..

Here's the full code :

import React, { useState } from "react";

// INTERFACES
interface Todo {
  id: number;
  text: string;
  completed: boolean;
}

export const TodoComponent = () => {
  // STATE
  const initialTodos: Todo[] = [
    { id: 0, text: "Todo 1", completed: false },
    { id: 1, text: "Todo 2", completed: true },
    { id: 2, text: "Todo 3", completed: false },
  ];

  const [todos, setTodos] = useState<Todo[]>(initialTodos);

  let [newTask, setNewTask] = useState<Todo>();

  // ACTIONS
  const handleClickOnComplete = (id: number, completed: boolean) => {
    const newTodos = [...todos];
    newTodos[id].completed = !completed;
    setTodos(newTodos);
  };

  const handleRemove = (todo: Todo) => {
    const newTodos = todos.filter((t) => t !== todo);
    setTodos(newTodos);
  };

  const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    setNewTask({
      id: todos.length,
      text: event.target.value,
      completed: false,
    });
  };

  const handleSubmitNewTodo = () => {
    const newTodos = [...todos];
    console.log(newTask, newTodos);
    newTodos.push(newTask);
    setTodos(newTodos);
  };

  return (
    <div>
      <h1>Todo App !</h1>

      <div>
        {todos.map((todo) => {
          return (
            <div key={todo.id}>
              {todo.id} - {todo.text} -{" "}
              <input
                type="checkbox"
                checked={todo.completed}
                onChange={() => handleClickOnComplete(todo.id, todo.completed)}
              />
              <button onClick={() => handleRemove(todo)}>Remove task</button>
            </div>
          );
        })}
      </div>

      <hr />

      <div>
        <input placeholder="Add todo" type="text" onChange={handleChange} />
        <button onClick={handleSubmitNewTodo}>Add todo</button>
      </div>
    </div>
  );
};

Problem is in handleSubmitTodo

Thanks for your help and advices. Take care.

4
  • 1
    Without running this myself I'm not sure, but how do you know newTask won't be undefined when you call newTodos.push(newTask)? You could write if (newTask) newTodos.push(newTask) to fix it? Not sure if that meets your needs or not. Commented Nov 29, 2021 at 19:56
  • your useState for newTask didnt defined a Todo-like object. You didnt pass one inital state, so undefined. Commented Nov 29, 2021 at 20:33
  • @jcalz I guess you're right. I don't have problem if I add a condition before pushing. Thanks. Commented Nov 29, 2021 at 21:08
  • @Sysix How to declare both Todo or undefined then ? At first I tried useState<Todo | undefined>() but it gives an error. Commented Nov 29, 2021 at 22:51

2 Answers 2

1

Updated

You can try this:

  const handleSubmitNewTodo = () => {
    let newTodos = [...todos];
    console.log(newTask, newTodos);
    if (newTask) {
      newTodos.push(newTask);
      setTodos(newTodos);
      setNewTask(undefined);
    }
  };

I have added the setNewTask to undefined to maintain the initial state after adding the new todo to the todo list.

Sign up to request clarification or add additional context in comments.

3 Comments

Why both if (newTask) and newTask && ?
Just did that by mistake :)
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
0

Adding a condition around the push seems to do the trick.

  const handleSubmitNewTodo = () => {
    const newTodos = [...todos];
    if (newTask) {
      newTodos.push(newTask);
    }
    setTodos(newTodos);
  };

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.