3

Here is the code

trying to compile it says "Argument of type 'toDo' is not assignable to parameter of type 'SetStateAction<toDo[]>'"

i cannot figure out how it is not working since the type seem to be correct.

How to avoid that error

  const [todoList, setTodoList] = useState<toDo[]>([])

  useEffect(() => {
    loadToDoList()
  }, [])

  const loadToDoList = async () => {
    const toDoList = await ToDoService.getToDoList()
    console.log(toDoList)

    setTodoList(toDoList)
  }

  return (
    <div>
      <ToDoList items={todoList} />
    </div>
  )
}```
Alberto3
  • 35
  • 2
  • 4

1 Answers1

1

This error is because you are trying to set the state with a variable with a type toDo when it expects an array of toDo toDo[].

Confirm that the type of toDoList returned by await ToDoService.getToDoList() is equal to toDo[] or change your generic type declaration on the useState call to const [todoList, setTodoList] = useState<toDo>([]), in case toDo is already an array.

Toni Bardina Comas
  • 1,670
  • 1
  • 5
  • 15
  • If they change the `useState` type declaration to `const [todoList, setTodoList] = useState([])` then there would still be a TS error. The generic type, `toDo`, is not an array, whilst you're assigning an empty array as the initial value. – Kapobajza Jul 15 '22 at 14:18
  • We cannot know which type is `toDo`. Since its the return type of a method called `getTodoList` , there are many chances it is an array – Toni Bardina Comas Jul 15 '22 at 14:25
  • Based on the error message "Argument of type **'toDo'** is not assignable to parameter of type 'SetStateAction< **toDo[]** >'" we certainly know that it's not an array. – Kapobajza Jul 15 '22 at 15:43
  • That's not true. `toDO` can perfectly be an array, then `toDo[]` would be an array of arrays. – Toni Bardina Comas Jul 15 '22 at 15:52